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();
});