There are 3 tables:
users
: id, name
compliments
: id, name
users_compliments
: id, compliment_id, user_id, complimentor_id
Here is my User model:
class User extends Model
public function sent_compliments() {
return
$this->belongsToMany(
'Compliment',
'users_compliments',
'complimentor_id',
'compliment_id'
)->withPivot('user_id');
}
here is an example response if I run $user->sent_compliments()->get()
Illuminate\Database\Eloquent\Collection {
all: [
Compliment {
id: 2,
name: "You are smart",
pivot: Illuminate\Database\Eloquent\Relations\Pivot {
user_id: 6,
id: 99,
},
},
Compliment {
id: 52,
name: "You are funny",
pivot: Illuminate\Database\Eloquent\Relations\Pivot {
user_id: 42,
id: 186,
},
},
],
}
but here is the response I want (it includes the actual User model instead of just the user_id in the pivot)
Illuminate\Database\Eloquent\Collection {
all: [
Compliment {
id: 2,
name: "You are smart",
pivot: Illuminate\Database\Eloquent\Relations\Pivot {
user_id: 6,
id: 99,
},
user {
id: 6,
name: "John"
}
},
Compliment {
id: 52,
name: "You are funny",
pivot: Illuminate\Database\Eloquent\Relations\Pivot {
user_id: 42,
id: 186,
},
user {
id: 42,
name: "Alex"
}
},
],
}
Is there a way to get this data with an eloquent eager load (like using the With::
command ) instead of iterating through the pivot, collecting the user_ids and manually querying the User
table?
sent_nominations
method – Alihossein shahabisent_compliments
method is posted in the question above. It's in theUser
model.public function sent_compliments()
@Alihosseinshahabi – Yaseen Anisssent_nominations
does not exist. It should besent_compliments
... I just updated the question and I apologize for the confusion – Yaseen Aniss