0
votes

I have a many-to-many pivot table set up between Recipes and Ingredients. For a particular Ingredient, I want a list of Recipies

$ingredientID = 99;

$recipies = Recipe::whereHas('ingredients', function ($q) use ($ingredientID) {
    $q->where('id', '=', $ingredientID);
})->get();

And that works. But in my case there's an extra column in the pivot table for "description". For instance a particular "cookie" recipe and "egg" ingredient connection might have the description: "make sure the eggs are really fresh for this recipe".

So how do I return that extra pivot table column with this query? I've tried going into the model files and adding "withPivot" calls like so:

public function ingredients() 
{
    return $this->belongsToMany('App\Ingredient')->withPivot("description");
}

But that doesn't work. Any idea how I can intimidate my whereHas query into coughing up this extra pivot-table column?

1
Your whereHas query already has that information since you used withPIvot(). You would just call (from a model picked from $recipies, like in a foreach) $recipie->pivot->description.N Mahurin
I've tried that- from the results of my whereHas query I've done a loop like this: foreach($recipies as $index=>$recipie) { Log::info("description: ".$recipie->pivot->description); } But then I get "trying to get property of a null object"CodeOwl

1 Answers

0
votes

To access the description pivot column you would do something like:

$recipies->first()->ingredients->first()->pivot->description;