Reputation: 3
😄 Hi!
Sorry the title isn't that explicite, but I'm a beginner and I really don't have the vocabulary just yet 😶
I've been struggling for hours with something, so before I trow my computer by the window, I came to ask for help :3
In my database I have a table with exhibitors and an other one with labels for those exhibitors. It's a many to many relationship and on my Controller I get the exhibitors with they labels that way :
$exposants = Expo::where('this_year', 1)->with('labels')->get();
It's working great! But now I want more!
I need to get the Exhibitors with a specific label. Let's say I want the exhibitors who would come this year with they labels {that part I already have} but only those who have the column "name" on the "label" table equal to "food". How do I do that ? 😅
Please help my 🙏
Upvotes: 0
Views: 50
Reputation: 12835
You can try
$exposants = Expo::where('this_year', 1)
->whereHas('labels', fn($q) => $q->where('name', $request->input('labelName'))
->with('labels')
->get();
//OR using non-arrow closure for PHP 7.3 and lower
$exposants = Expo::where('this_year', 1)
->whereHas('labels', function($q) use($request){
$q->where('name', $request->input('labelName'));
})
->with('labels')
->get();
//replace labelName with whatever key you have on request
Laravel docs: https://laravel.com/docs/8.x/eloquent-relationships#querying-relationship-existence
Upvotes: 1