Achraf Ghellach
Achraf Ghellach

Reputation: 2174

Common model_id for two Models - Laravel 5 - Eloquent

I have a question that I'm looking for its answer for a while. Well, in my Laravel Project, I have a Model Disease which has a belongstoMany relationship with Recipe and User Models. I'm looking to fetch from database all recipe rows that have same disease_id as the current logged user. Is there any way to do so with Eloquent? Thank you !

Upvotes: 0

Views: 201

Answers (2)

Mike Harrison
Mike Harrison

Reputation: 1383

Make sure your User model has a diseases relation defined:

public function diseases()
{
    return $this->hasMany(Disease::class);
}

You can get the current user and disease_id like this (edited to use the diseases relation on the Users model):

$user = Auth::user();
$disease_ids = $user->diseases()->pluck('id');

Then you can find the recipes with the same disease_id like this:

return Recipe::whereIn('disease_id', $disease_ids)->get();

Upvotes: 1

Brad Goldsmith
Brad Goldsmith

Reputation: 293

Would something like this work:

$user = Auth::user();
return Recipe::where('disease_id', $user->id)->get();

Upvotes: 0

Related Questions