Can i show in Blade #10
-
Hi, thanks for your awesome trait. How can i show in blade if a model has like? Please forgive my poor english |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Hi @mchisnerman3 ! $model
->likers()
->whereKey($user->getKey())
->exists();
$model
->likers()
->whereKey(auth()->id())
->exists(); Alternatively, you could implement an accessor in your markable model: public function getHasLikeAttribute()
{
return $this
->likers()
->whereKey(auth()->id())
->exists();
} and use it in your blade component: $model->has_like; Beware: using the accessor will lead you to the N+1 problem when working with multiple models at once. $models = Model::query()
->withCount([
'likers as has_like' => fn ($query) => $query->whereKey(auth()->id())
])
->withCasts([
'has_like' => 'boolean'
])
->get(); Hope this can help you! |
Beta Was this translation helpful? Give feedback.
Hi @mchisnerman3 !
Sure, you can do that in many ways I think. A solution I came up with is something like this:
Alternatively, you could implement an accessor in your markable model:
and use it in your blade component:
Beware: using the accessor will lead you to the N+1 problem when working with multiple models at once.
In that case, you could easily append the has_like attribute while executing the query: