Answer the question
In order to leave comments, you need to log in
How to display models with a pre-calculated value without unnecessary requests?
I am writing a functionality for saving posts by users.
There are User, Post models with a many-to-many relationship through the 'saved_post_user' table.
In the User model, a relationship that receives the saved posts from the user:
public function savedPosts()
{
return $this->belongsToMany('App\Models\Post', 'saved_post_user');
}
public function savedUsers()
{
return $this->belongsToMany('App\Models\User', 'saved_post_user');
}
public function posts()
{
$data['posts'] = Post::orderBy('rating', 'desc')->with('comments')->get();
return view('posts', $data);
}
@if ($post->savedUsers->contains(Auth::id()))
<strong>Пост сохранен</strong>
@endif
@if ($post->saved)
<strong>Пост сохранен</strong>
@endif
$post->title
$post->rating
...
$data['posts'] = Post::orderBy('rating', 'desc')->with('comments')->get();
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question