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

darkdevelop's avatar

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;
    }
0 likes
6 replies
Sinnbeck's avatar
ublic function recipes($id){
        $data = DB::table('recipe_tag')
                     ->select('recipe_id')
                     ->whereIn('tag_id', $id)->get();
        return $data;
    }
1 like
Snapey's avatar

or eloquent

$tag = Tag:with('recipes')->findOrFail($id);
darkdevelop's avatar

Any tip what should I add to get only array of corresponding recipe_id's (not collection)?

darkdevelop's avatar

It returns:

BadMethodCallException Call to undefined method Illuminate\Database\Query\Builder::toArray()

Sinnbeck's avatar
Sinnbeck
Best Answer
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.