Basically I have users who belongs to many users. We can imagine friendship relations between users.
So I have a pivot table for the relation, with the id's of 2 users and one additionnal field 'created_at'.
users table: id, name
friend_user table : user_id, friend_id, created_at
In my User model, i have a friends function which returns a collection of users :
public function friends() {
return $this->belongsToMany(User::class, 'friend_user', 'user_id', 'friend_id');
}
My goal is to get the list of every relation between users. With a loop on User::all(), I can easily get all those relations, user after user :
$users = User::all();
foreach ( $users as $user ) {
foreach ( $user->friends as $friend ) {
return [$user->name . 'is friend with ' . $friend->name];
}
}
But I would like to get them ordered by 'created_at', indifferently the user who is in the relation.
Is there an easy way to do this with eloquent or maybe another way ?
Thanks for your help.