R
R
root092021-07-07 18:25:27
Laravel
root09, 2021-07-07 18:25:27

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

bookmarkCached() is a mutator that holds the bookmarks link cached and translated into an array with post ids.

How to do it right and optimize?

In the User model
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;
        });
    }


I look through the laravel debugbar, without these functions in the timeline section of the application graph 200ms speed, and with these functions 450ms, as I understand it is very bad?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
N, 2021-07-07
@root09

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{
        
        // Добавить
        
    }
    
}

J
jazzus, 2021-07-07
@jazzus

$posts = Post::withExists(['bookmarks' => function ($query) {
    $query->where('user_id', Auth::id());
}])
    ->get();

check in view
$post->bookmarks_exists

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question