Have you checked the documentation? I think it explains this quite well.
https://laravel.com/docs/5.4/eloquent-relationships#querying-relationship-existence
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I have Company and each of them would be assigned with Categories (many to many).
How do I query the company based on the specific Categories.
In Laracasts, I have only learned this:
public function searchtest(Request $request)
{
return Company::with('categories')->has('categories')->get();
}
This only return companies that has categories. How do I query company that has a category of Electronics or Education?
one more thing. I need to learn some advanced search function that can do filters of varying relationships. can someone lead me to a tutorial? thanks
You should use the whereHas() method:
$electronicsCompanies = Company::whereHas('categories', function ($query) {
$query->where('name', 'Electronics'); // assuming The Category model has a property called 'name'
} );
Link to documentation (Scroll to subheading "Querying relationship existance", then look for the last code example)
Please or to participate in this conversation.