First what comes to mind is just $user->badges()->recipes
. Have you tried that?
Hey Xum, thanks for your answer! If I try that it says "Undefined property: lluminate\Database\Eloquent\Relations\BelongsToMany::$recipes"
Also I already filter the recipes beforehand. I would like to concatenate the filter descriped above to the previous ones. Therefore, it would be very helpful if the solution does not start with $user. I want something like this: $recipes->...
joneswack said:
MY PROBLEM I am trying to filter the recipes table so that the recipe's badges match the user's badges. So the Recipe Model as well as the User Model have a belongsToMany('Badge') relation.
Your controller filter the recipes table
So you can use in badge Model
public function recipes()
{
return $this->belongsToMany('Recipe');
}
UserModel
public function badges()
{
return $this->belongsToMany('Badge');
}
Then you can user
foreach($user->badges()->recipes as $recipe){
......
}
@joneswack, Yes, you need to define relations first, like in @tuyenlaptrinh's post.
And chain your filters to that expression:
$recipes = $user->badges()->recipies()->where('this', '=', 'that')->orWhere('yumminess', '>=', '9000')->get();
Hey guys, thanks for your answers. I am sure they work, too. But I needed something that could be concatenated to my previous filters. I had a few recipes already which needed to be filtered again. Therefore the command should start with recipe->...
I found the following solution that seems to work fine:
Recipe::join('badge_recipe as br', 'br.recipe_id', '=', 'recipes.id') ->join('badge_user as bu', 'bu.badge_id', '=', 'br.badge_id')->where('bu.user_id', '=', Auth::user()->id);
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community