I have 3 tables:
userstablepoststable (users can have many posts)likestable (works in the same way that Facebook likes do)
I have the following relationships:
User.php:
public function posts()
{
return $this->hasMany('App\Post');
}
Post.php:
public function user()
{
return $this->belongsTo('App\User');
}
public function likes()
{
return $this->hasMany('App\Like');
}
Like.php:
public function post()
{
return $this->belongsTo('App\Post');
}
To get all posts, I do:
$posts = Post::with('likes')
->get();
However, this returns all likes associated with the post (which I don't want). What I need to be able to do is check if the logged in user has liked each post.
For example, in my view, I have:
@foreach ($posts as $post)
// check if logged in user liked the $post
@endforeach
How can I modify my code so that I can check if the user has liked each post and how can I do this by simply adding a new relationship?
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire