O
O
Omniverse2017-03-15 00:42:35
Laravel
Omniverse, 2017-03-15 00:42:35

How to get all posts liked by a user in Laravel?

Hello.
I have models: User, Post, Videos.
I want to make it possible to like posts and videos and then get a list of posts/videos that a particular user has "liked".
Here's the structure I've settled on so far.

posts
    id - integer
    title - string

videos
    id - integer
    title - string

likes
    id - integer
    user_id - integer
    likeable_id - integer
    likeable_type - string

Created a Like model, defined relationships in this way.
class User extends Model
{
   public function posts()
    {
        return $this->hasMany(Post::class);
    }

    public function videos()
    {
        return $this->hasMany(Video::class);
    }
}

class Post extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }
   
    public function likes()
    {
        return $this->morphMany(Like::class, 'likeable');
    }
}

class Video extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }
   
    public function likes()
    {
        return $this->morphMany(Like::class, 'likeable');
    }
}

class Like extends Model
{
    public function likeable()
    {
        return $this->morphTo();
    }
}

How to get all posts/videos that a user has "liked"?
Is this structure and relationship correct?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
Anton, 2017-03-15
Reytarovsky @Antonchik

It would be more correct to create separate tables for post likes and video likes. Then make two functions in the user class that return hasMany likes of the video or post, and through the like already receive the post or video

A
Alexander Aksentiev, 2017-03-15
@Sanasol

well, you probably need to do user -> hasMany -> likes
and then filter by likeable_type when getting user likes.

C
cha-cha, 2017-03-15
@cha-cha

hasManyThrough

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question