R
R
Roman2019-02-10 04:22:19
Laravel
Roman, 2019-02-10 04:22:19

Laravel, how to filter posts with many-to-many relationship in pagination?

Hello. I’ve been struggling for two hours now :(
There are many-to-many relationships (belongsToMany), entries in the pivot table are normal.
Now, when displaying a list of entries through paginate(), I need to filter out those that have a relationship with the current logged in user (I want mark them in the view in a special way, they are listed there).
I can get the user object. I also have access to the properties of the records. But for some reason all my conditions don’t work. I just haven't tried it..
How can this be done through Eloquent?
Thanks.PS
.

$pages = Page::paginate(5); //
      
      foreach($pages as $page){ 
        
        $danger_or_success[$page->id]['state'] = 'danger';
        $danger_or_success[$page->id]['text'] = 'On';
        
  
        if(true) { // что мне сюда вместо true написать, чтобы оно было верно только для $page имеющих отношение к текущему User::find(1) 
          
          $danger_or_success[$page->id]['state'] = 'success';
          $danger_or_success[$page->id]['text'] = 'Off';
        }
        
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman, 2019-02-10
@procode

!!! after a lot of googling, I found the answer over which the best minds of mankind fought!))
it looks something like this:

$client = Client::find(1);
$exists = $client->products->contains($product_id);

from here: https://stackoverflow.com/questions/24555697/check...
works for me. thanks to all!

N
NubasLol, 2019-02-12
@NubasLol

As a quick option

::withCount(['users' => function ($query) {
    $query->where('id', auth()->id());
}]);

Then in the template you will look if the number is not 0

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question