Answer the question
In order to leave comments, you need to log in
How to check if a post is bookmarked by a user?
There is a page where posts are displayed, there is a user, the user has a Bookmark model that stores bookmarks for posts. (user_id, post_id)
On the page with a list of posts, you need to show a button to add / remove a bookmark to a post, depending on whether it is bookmarked or not.
How to do it right?
Now my posts are displayed through foreach and I just added a check inside, but this gives a load.
@foreach($posts as $post)
<div class="post">
@if(Auth::check() && isset(Auth::user()->bookmarkCached[$post->id]))
<button>Удалить закладку</button>
@else
<button>Добавить закладку</button>
@endif
</div>
@endforeach
public function bookmarks()
{
return $this->hasMany('App\Models\Bookmark');
}
public function getBookmarkCachedAttribute()
{
return Cache::remember('bookmarks_cached_list_'.$this->id, 3600, function () {
$arr = $this->bookmarks->toArray();
$new_arr = [];
foreach ($arr as $item)
{
$new_arr[] = $item['post_id'];
}
return $new_arr;
});
}
Answer the question
In order to leave comments, you need to log in
In the post model, you need to add a relation with reference to the users who added them... in my code it's bookmark_users ...
<?php
$CURRENT_USER_ID = \Auth::user()->id;
$posts = Post::with([
'bookmark_users' => function($q) use($CURRENT_USER_ID) {
$q->where('id', $CURRENT_USER_ID);
}
])
->get();
foreach ($posts as $item) {
if($item->bookmark_users->count() > 0) {
// Удалить
}else{
// Добавить
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question