ublic function recipes($id){
$data = DB::table('recipe_tag')
->select('recipe_id')
->whereIn('tag_id', $id)->get();
return $data;
}
Oct 9, 2019
6
Level 1
Using Query Builder in foreach loop
I have table named "recipe_tag" which is pivot table. In there I have 2 collumns named: "recipe_id" and "tag_id". Table is allready seeded and filled with data. every tag can have multiple recipes. I'm trying to get all recipes_id according if user passed array ($id) of tags where i want to get corresponding recipe_id. It works only on first element of $id array. If I pass array of 2+ elements I get empty collection(which i will turn into array). Here is code, every suggestion is more than welcomed.
public function recipes($id){
$data = DB::table('recipe_tag')
->select('recipe_id')
->where(function($query) use($id)
{
foreach($id as $item)
{
$query->where('tag_id', '=', $item);
}
})->get();
return $data;
}
Level 102
Seems that you called it instead of ->get(). Do this :)
public function recipes($id){
$data = DB::table('recipe_tag')
->select('recipe_id')
->whereIn('tag_id', $id)->get()->toArray();
return $data;
}
1 like
Please or to participate in this conversation.