Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

msyaukat's avatar

Many to Many Query

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

0 likes
4 replies
PaulClarke's avatar

You need to use whereHas in your query and then apply the constraints in a closure. Something like this:

public function searchtest(Request $request)
{          
return Company::with('categories')
            ->whereHas('categories', function($q) {
                $q->where('category', 'electronics')
                   ->orWhere('category', 'education');
            })
            ->get();
}

Obviously I am not sure what precisely your fields are called, but you might be able to adapt this.

1 like
ChristophHarms's avatar
Level 18

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)

1 like
msyaukat's avatar

thanks a lot guys. I will try this. I have no idea what to search for in the documentation.

1 like

Please or to participate in this conversation.