To define a connection between two users in Laravel, you can use a many-to-many relationship with a pivot table. However, in this case, you need to check both user_1 and user_2 columns in the pivot table.
Here's how you can achieve this:
-
Create a pivot table with user_1 and user_2 columns. You can use the
php artisan make:migrationcommand to create a migration for the pivot table. -
In your User model, define the many-to-many relationship with the pivot table. You can use the
belongsToManymethod and specify the pivot table name and the column names for user_1 and user_2.
class User extends Model
{
public function friends()
{
return $this->belongsToMany(User::class, 'pivot_table_name', 'user_1', 'user_2')
->orWhere(function ($query) {
$query->where('user_2', $this->id);
});
}
}
- Now, you can retrieve the friends of a user by calling the
friendsmethod on the User model.
$user = User::find(1);
$friends = $user->friends;
This will return a collection of User models representing the friends of the user.
Note: The orWhere method is used to check both user_1 and user_2 columns in the pivot table.