How do I know if the signed in user has “liked” a Post
, Url
or News
?
I have a morphTo
relation between a couple of models both for comments, images and likes. But I haven’t figured out how to use it with likes.
In my Like
model, I have the following relation:
public function likeable()
{
return $this->morphTo();
}
The migration for Like
model:
Schema::create('likes', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->onDelete('cascade');;
$table->integer('likeable_id');
$table->integer('likeable_type');
$table->timestamps();
});
So far so good I assume - just basic standard docs boilerplate. And for Post
, Url
and News
I have the following relation:
public function likes()
{
return $this->morphOne(Like::class, 'likeable');
}
In my Livewire ContentComponent
I have the following render()
method:
public function render()
{
$collection = collect();
$posts = Post::search('topic', $this->search)->withCount(['comments', 'likes'])->with('user')->latest()->get();
$urls = Urls::search('topic', $this->search)->withCount(['comments', 'likes'])->with('user')->latest()->get();
$news = News::search('topic', $this->search)->withCount(['comments', 'likes'])->latest()->get();
/** Push posts to the collection */
foreach ($posts as $post) $collection->push($post);
/** Push urls to the collection */
foreach ($urls as $item) $collection->push($item);
/** Push news to the collection */
foreach ($news as $item) $collection->push($item);
$collection->each(function ($item, $key) {
// dd($item);
});
return view('livewire.content-component', [
'urls_news_and_posts' => $collection->sortByDesc('created_at')->sortByDesc('sticky')->paginate(20)
]);
}
This is were I encounter my problem
Im able to count all the likes for each specific model. But somehow I need to be on the frontend know that the user has liked the model. I was trying to add a key to $collection
in the render()
method, something like (bool) user_as_liked
- but here my “programming” skills fail me.