E
E
elailasou2015-12-04 12:09:03
Laravel
elailasou, 2015-12-04 12:09:03

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');
    }

In the Post model, the link that gets the users who have saved the post:
public function savedUsers()
    {
        return $this->belongsToMany('App\Models\User', 'saved_post_user');
    }

Function in the controller to display posts:
public function posts()
    {
        $data['posts'] = Post::orderBy('rating', 'desc')->with('comments')->get();
        return view('posts', $data);
    }

Well, in the template I display posts in a cycle.
The task is to display at the post whether the current post is saved by an authorized user or not.
You can do it in the post loop like this:
@if ($post->savedUsers->contains(Auth::id()))
       <strong>Пост сохранен</strong>
@endif

But this generates a bunch of unnecessary queries to the database.
Ideally, I should display posts like this:
@if ($post->saved)
       <strong>Пост сохранен</strong>
@endif
$post->title
$post->rating
...

It turns out that you need to shove something into the function for displaying posts in the controller, but I’ll never know what.
$data['posts'] = Post::orderBy('rating', 'desc')->with('comments')->get();

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
Tesla, 2015-12-07
@junk1114

Well, you use eager loading of comments so as not to produce requests. Why not add users there as well with('comments', 'savedUsers')? If you get too many lines, you can limit the .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question