D
D
Dimon3x2019-04-05 22:23:27
Laravel
Dimon3x, 2019-04-05 22:23:27

How do I know if an article has been bookmarked?

Tables:
posts
users
posts_user - intermediate - bookmarks

$table->bigIncrements('id');
$table->integer('user_id');
$table->integer('post_id');

I remove all articles
$allPosts = Posts::with('users')->get();
class Posts extends Model
{ 
    //получить автора статьи
    
    public function users()
    {
        return $this->hasMany('App\User', 'id', 'user_id');
    }

I don’t know what needs to be done to add a key to the request, so that
later in the loop it will be displayed that the article has already been added, otherwise bookmark it.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jazzus, 2019-04-06
@jazzus

In the controller

$id = Auth::id();
//К каждой статье добавляем users_count, 
//чтобы узнать какие статьи уже добавлены в избранное авторизованного юзера
// и не делать потом запросы к бд в цикле
$posts = Post::with('users')
           ->withCount(array('users' => function($query) use ($id) {
           $query->where('users.id', $id);
           }))->get();

In template
{{-- если количество больше нуля, значит статья уже добавлена в избранное --}}
@foreach ($posts as $post)
  @if ($post->users_count>0)
    Уже добавлено в избранное
  @else
    Добавить в избранное
  @endif
@endforeach

Fix relationship in Post model
public function users() {
  return $this->belongsToMany('App\User', 'posts_user', 'post_id', 'user_id');
}

Add to favorites via attach. How it's done

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question