chrisgrim's avatar

How do I filter the eager loading results?

Hi All,

I am trying to understand how to filter my eager loaded results. In my show method on my category controller I have

public function show(Category $category)
    {
         $category->load('events');
        
        return view('category.show', compact('category'));
    }

This returns my current category with the eager loaded events so my relationships are working. My question is how do I filter those returned events. I guess I should use a where() method but when I use

$category->load('events')->where('approved', Null)->get();

It is searching my categories class for the approved column, not my events class. Is there a way to tell Laravel to search the eager loaded class?

Thanks!

0 likes
8 replies
chrisgrim's avatar

Hi @manelgavalda

When I use

public function show(Category $category)
    {
        $category->load('events')->whereHas('events', function($query) {
                $query->where('approved', !Null);
            })->get();
        
        return view('category.show', compact('category'));
    }

It is still returning all the events, even the ones with Null. I have also been looking into adding a method on my category.php file like

function eventFiltered()
    {
          return $this->
              hasMany(Event::class)
              ->wherePivot('approved', !null );
     }

Would this also be another solution?

manelgavalda's avatar

@CHRISGRIM - You can pass a closure to the loaded class, and maybe this will work for you:

$category = $category->load(['events' => function ($query) {
    $query->whereNotNull('approved');
}])->get();

Does it work?

chrisgrim's avatar

Hi @manelgavalda

I tried using

public function show(Category $category)
    {  
        $category = $category->load(['events' => function ($query) {
    $query->whereNotNull('approved');
}])->get();
        
        return view('category.show', compact('category'));
    }

and got the issue

"Property [categoryName] does not exist on this collection instance.
Snapey's avatar
Snapey
Best Answer
Level 122
       $category->load(['events' => function ($query) {
           $query->whereNotNull('approved');
        }])->get();

remove $category=

1 like
chrisgrim's avatar

That did it! Just to understand, why did removing the $category = fix it?

Thanks Chris

chrisgrim's avatar

Gotcha! Thank you so much for taking the time to explain. :)

Please or to participate in this conversation.