$table->bigIncrements('id');
$table->integer('user_id');
$table->integer('post_id');$allPosts = Posts::with('users')->get();class Posts extends Model
{
//получить автора статьи
public function users()
{
return $this->hasMany('App\User', 'id', 'user_id');
}class Post extends Model
{
/**
* Автор статьи.
*/
public function author()
{
return $this->belongsTo('App\User', 'id', 'user_id');
}
/**
* Ищем в промежуточной таблице, запись о том, что текущий пользователь добавил эту статью в закладки.
*/
public function bookmark()
{
return $this->belongsTo('App\Bookmark', 'post_id')->where('user_id', optional(auth())->id);
}
public function getIsBookmarkAttribute()
{
return !is_null($this->bookmark);
}
}
// Контроллер
$allPosts = Posts::with('author', 'bookmark')->get();
// Шаблон
@foreach ($posts as $post)
@if ($post->is_bookmark)
В избранном
@else
Добавить в избранное
@endif
@endforeach $id = Auth::id();
//К каждой статье добавляем users_count,
//чтобы узнать какие статьи уже добавлены в избранное авторизованного юзера
// и не делать потом запросы к бд в цикле
$posts = Post::with('users')
->withCount(array('users' => function($query) use ($id) {
$query->where('users.id', $id);
}))->get();{{-- если количество больше нуля, значит статья уже добавлена в избранное --}}
@foreach ($posts as $post)
@if ($post->users_count>0)
Уже добавлено в избранное
@else
Добавить в избранное
@endif
@endforeachpublic function users() {
return $this->belongsToMany('App\User', 'posts_user', 'post_id', 'user_id');
}$table->integer('post_id')->unsigned();
$table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');class Posts extends Model
{
//получить автора статьи
public function users()
{
return $this->hasMany('App\User', 'id', 'user_id');
}
//добавлен ли вопрос в закладки
public function bookmark()
{
return $this->belongsToMany('App\User');
}
}<div class="bookmark">
@if($post->bookmark->count() != 0)
@foreach($post->bookmark as $aaa)
@if(Auth::id() == $aaa->id)
<button data-bookmark="{{$post->id}}" class="for-desctop">Удалить из закладок</button>
@else
<button data-bookmark="{{$post->id}}" class="for-desctop">Добавить в закладки</button>
@endif
@break
@endforeach
@else
<button data-bookmark="{{$post->id}}" class="for-desctop">Добавить в закладки</button>
@endif
</div> @if($post->bookmark->count() != 0)return $this->belongsToMany('App\User');public function users() {
return $this->belongsToMany('App\User', 'posts_user', 'post_id', 'user_id');
}$table->integer('post_id')->unsigned();
$table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');