0
votes

I'm building an app with Laravel as my front end and Angular as my back end. I'm implementing a Like system on posts and comments users make. I have a polymorphic relationship with my like system because users can like posts + comments. My Models look like this:

Like Model

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

Post Model

class Post extends Model {
    public function user()
    {
    return $this->belongsTo('App\Models\User', 'author_id');
    }

    public function likes()
    {
    return $this->morphMany('App\Models\Like', 'likeable');
    }
}

Comment Model

class Comment extends Model
{
    public function likes()
    {
    return $this->morphMany('Like');
    }
}

I'm confused how to go about this. When I load a post or a comment, I want to retrieve the post details (which I can already retrieve) + the like count and who's liked it. How do I eager load the 'Like' data with the post? Should I even use Polymorphic relations here? Thanks in advance!

My Like table looks like this:

   Schema::create('likes', function(Blueprint $table) {
        $table->increments('id');

        $table->integer('user_id'); // User who does the liking 
        $table->integer('likeable_id'); // User whose Comment/Post is liked 
        $table->string('likeable_type'); // Item that is being liked
                                        //   Could be Comment or Post (Models)
        $table->timestamps();
    });
1

1 Answers

1
votes

This is something I'm also looking into at the moment. In the source code (at first glance) it says that it doesn't load a morphTo on an eager load, it just passes a dummy query.

As far as eager loading from the Post or Comment side of things you should be fine i.e.

$posts = Post::with('likes')->get();
$comments = Comment::with('likes')->get();

Further more, as you only need the count and not each row of likes something like this would be worth looking at.

Hope this helps!