Answer the question
In order to leave comments, you need to log in
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
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();
}
}
Answer the question
In order to leave comments, you need to log in
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
well, you probably need to do user -> hasMany -> likes
and then filter by likeable_type when getting user likes.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question