$contacts = Contact::whereHas('roles', function ($query) {
$query->where('id', 5);
})->get();
Docs: https://laravel.com/docs/8.x/eloquent-relationships#querying-relationship-existence
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
In my Contact.php I have the relationship defined as:
...
public function roles()
{
return $this->belongsToMany('App\Models\contact\ContactRole');
}
...
in my controller, I have this query:
...
$data = Contact::select("id", "company_id", "first_name", "last_name")
->where('first_name', 'LIKE', "%$search%")
->orWhere('last_name', 'LIKE', "%$search%")
->get();
...
and I'm trying to get Contacts that have a roles()->where('id', 5)
My roles table has two column, 'id' and 'name'. Should I not be using the id to search and instead look for the matching name column? Pivots are so confusing to me. The matching name to 'id' record 5 is 'PM Contact'. I wonder if I should be trying to match that instead of the id. Help!
Edit: Normally I'd google it, but trying to query google for "laravel with examples" get me example sof laravel not specifically the "with" statements.
$contacts = Contact::where(function ($query) use ($search) {
$query->where('first_name', 'like', "%{$search}%")->orWhere('last_name', 'LIKE', "%{$search}%");
})->whereHas('roles', function ($query) {
$query->where('id', 5);
})->get();
With select, but I don't think that it is necessary.
$contacts = Contact::select('id', 'company_id', 'first_name', 'last_name')->where(function ($query) use ($search) {
$query->where('first_name', 'like', "%{$search}%")->orWhere('last_name', 'LIKE', "%{$search}%");
})->whereHas('roles', function ($query) {
$query->where('id', 5);
})->get();
Please or to participate in this conversation.