salfel's avatar

User Friendship Relation

Hi there, i started a new project, in which i have to define a connection between two users. So what i had first in mind was creating a belongstomany relationship which was pretty good, but then i stumbled upon the problem that how could i define it, that it searches both users because my pivot table would have user_1 and user_2 but how can i ask laravel to check for both, so not just if user_1 === user->id but also user_2 === user->id appreciate any help

0 likes
1 reply
LaryAI's avatar
Level 58

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:

  1. Create a pivot table with user_1 and user_2 columns. You can use the php artisan make:migration command to create a migration for the pivot table.

  2. In your User model, define the many-to-many relationship with the pivot table. You can use the belongsToMany method 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);
            });
    }
}
  1. Now, you can retrieve the friends of a user by calling the friends method 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.

Please or to participate in this conversation.