php – Querying MorphToMany Relation Laravel-ThrowExceptions

Exception or error:

The thing I want to get from the database is that get all the posts with the data which will identify whether the post is liked by the auth()->user() or not. Most probably via count.


public function likes()
    return $this->morphToMany('App\User', 'likeable');


public function likePosts()
    return $this->morphedByMany('App\Post', 'likeable')->withTimestamps();

Likeables Table

Likeables table has ('user_id', 'likeable_id', 'likeable_type')

I tried using orWhereHas

$posts = Post::with( ['user', 'tags', 'category'])->orwhereHas('likes', function($q) {
                    $q->where('user_id', auth()->id());

But with about query I am only getting those posts which the user has liked. I want to get all posts and a check whether the post is liked by the user or not

I came across whereHasMorph but it was only for morphTo and not for morphToMany.

How to solve:

Leave a Reply

Your email address will not be published. Required fields are marked *