it's easier (on your code as well later) if you keep your method names in someMethodName syntax, and keep the singular and plural names the same as their return results.
So I'd rename the method Like to likes
Also, remember that you will now be coding like foreach($post->likes as $like) but the $like is actually a user object ?
I would do it like this:
// Post.php
public function likes() {
return $this->hasMany(Like::class);
}
public function likedBy() {
return $this->belongsToMany(User::class , 'user_post_likeble' , 'post_id' , 'user_id');
}
public function getIsLikedAttribute()
{
return $this->likes->where('user_id', auth()->id())->count() > 0;
}
// Like.php
protected $table = 'user_post_likeble';
public function post() {
return $this->belongsTo(Post::class);
}
public function user() {
return $this->belongsTo(User::class);
}
// User.php
public function likedPosts() {
return $this->belongsToMany(Post::class , 'user_post_likeble' , 'user_id', 'post_id');
}
public function likes() {
return $this->hasMany(Like::class);
}
So now you have:
- Post, Like and User objects
- Posts haveMany Likes, and are likedBy many Users.
- Likes belong to both a User and a Post.
- Users have many likedPosts and many Likes.
And you should be able to do some stuff like:
// gets a single post with all likes and the associated user accounts
$post = Post::with('likes.user')->find(1);
// Or if you want a list of a few posts, and foreach see if the current user has liked this post
$posts = Post::with('liked')->limit(10)->get();
foreach($posts as $post) {
echo $post->id ." = ". $post->is_liked ."\r\n";
}
Getting the posts that the current user liked is even easier:
$likedPosts = auth()->user()->likedPosts;
dd($likedPosts->toArray());