Look up hasManyThrough on the Laravel docs. You may be able to set up the relationship on your users model then maybe set a query scope to get the data you need all in one go.
How to include data from third table in eloquent relationships?
I have the following tables:
users
id
name
items
id
name
type
fav_items
id
user_id
item_id
I have the following Models for users and fav_items tables:
User.php
---
class User extends Model {
protected $table = 'users';
public function fav()
{
return $this->hasMany('App\FavItems');
}
}
===========================
FavItems.php
---
class FavItems extends Model {
protected $table = 'fav_items';
}
So I can access all favorite items that authenticated user has added via Auth::user()->fav and this will return the following:
[
{
"id": 1,
"user_id": 3,
"item_id": 140
},
{
"id": 2,
"user_id": 3,
"item_id": 32459
},
{
"id": 3,
"user_id": 3,
"item_id": 43449
},
{
"id": 4,
"user_id": 3,
"item_id": 44425
}
]
How do I include name and type from items table into returned results? I'm not clear which relationship and in which model I should indicate to be able to achieve that.
Now that I looked closer your fav table is like a pivot. Setting a belongsToMany on your user and items model should achieve the results. You can add ->pivot() and set which columns to also return from the favs table if needed.
Please or to participate in this conversation.