Home > Blockchain >  Laravel eloquent with and with condition
Laravel eloquent with and with condition

Time:11-05

I'm trying to get category and selected items from category. Here is my code:

$reqItems = $request->items; //array - selected item
$categories = Category::where('type_id', 1)
     ->whereHas('items', function ($query) use ($reqItems){
         $query->whereIn('id', $reqItems);
     })
    ->with('items');
    ->get();

But this will return all the items, even not in selected item.

And i tried with foreach, its return null

$reqItems = $request->items; //array - selected item
$categories = Category::where('type_id', 1)->with('items');
foreach($reqItems as $reqItem) {
   $categories = $categories->whereHas('items', function ($query) use ($reqItem){
       $query->where('id', '=', $reqItem);
   });
}
$categories = $categories->get();

How to return only selected items?

CodePudding user response:

As suggested by @lagbox, here the working code:

$reqItems = $request->items;
$categories = Category::where('type_id', 1)
->with(['items' => function ($query) use ($reqItems){
        $query->whereIn('id', $reqItems);
    }])->get();

CodePudding user response:

when you wish to eager load a relationship and specify additional query conditions for the eager loading query. You can accomplish this by passing an array of relationships to the with method where the array key is a relationship name and the array value is a closure that adds additional constraints to the eager loading query:

  $categories = Category::where('type_id', 1)
        ->whereHas('items', function ($query) use ($reqItems){
            $query->whereIn('id', $reqItems);
        })
        ->with(['items'=>function ($query) use ($reqItems){
            $query->whereIn('id', $reqItems);
        }])
    ->get();
  • Related