Skip to content
Advertisement

Show the users that I liked using Laravel

I’m working on a small project using Laravel, and I would like to create a like and dislike system, so a user can like one to many more users.

I already have a table called Users (default by Laravel), now I have created another table called favorite_user with id, user_id and liked_the_user.

How can I get all the users that a user already liked? Is my table correct or should I change something?

All what I want to do is add like and show the people I liked. I don’t know how to make this relationship since I am new to Laravel.

Thank you

Advertisement

Answer

Looks like you have a pivot table there so a Many to Many relationship is what you need to setup. You will need to pass some additional arguments since the naming won’t fit with convention.

User Model:

// users the user has liked
public function liked()
{
    return $this->belongsToMany(self::class, 'favorite_user', 'user_id', 'liked_the_user');
}

// users who like the user
public function likes()
{
    return $this->belongsToMany(self::class, 'favorite_user', 'liked_the_user', 'user_id');
}

Controller:

public function liked(Request $request)
{
    // get liked users for current user
    $liked = $request->user()->liked;

    // get liked users for an arbitrary user
    $liked = User::findOrFail(...)->liked;

    ...
}

Laravel 8.x Docs – Eloquent – Relationships – Many to ManybelongsToMany

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement