Laravel With and wherePivot
eloquent, laravel, php, pivot
Solution
First, for reasons I'm unsure of, you need to add `withPivot('main_contact');` to your relation. This will return `main_contact` in your collection under `pivot`
class Company extends Model
{
public function mainContact()
{
return $this->belongsToMany('App\Contact', 'company_contacts')
->withPivot('main_contact');
}
}
The second thing you need to do is use `withPivot()` while constraint eager loading like so:
$companies = Company::with(['mainContact'=> function($query){
$query->wherePivot('main_contact', 1);
}])->get();
I've checked it, it works.
Just to go a bit above and beyond. Sometimes you'll want to query a pivot table without knowing the value. You can do so by:
$companies = Company::with(['mainContact'=> function($query) use ($contact){
$query->wherePivot('main_contact', $contact);
}])->get();
Problem
I'm trying to extract all companies and contacts with pivot.main_contact = 1. Tables: ``` Company: id, name Company_contacts: id, company_id, contact_id, main_contact Contacts: id, name ``` Model: ``` class Company extends Model { public function mainContact() { return $this->belongsToMany('App\Contact', 'company_contacts') ->wherePivot('main_contact', '=', 1); } } ``` Controller: ``` $query = Company::with('mainContact')->get(); ``` This returns companies + ALL contacts for the companies and NOT ONLY the ones with main_contact = 1.