C. Gill
C. Gill

Reputation: 175

Where clause not filtering

In my model I have the following two functions:

public function Children()
{
    return $this->hasMany(Menu::class, 'parent_menu_id', 'id');
}

public function ActiveChildren()
{
    $securityLevel = Auth()->User()->security_level_id;
    $activeChildren = Menu::Children()
        ->where('active_', TRUE)
        ->where('security_level_id', $securityLevel);

    return $activeChildren;
}

Children() returns a list of all Menu items where their parent_menu_id matches the id of this record. This is used in Nova for setup purposes.

With ActiveChildren() I am trying to create a filtered list of items for the actual menu where active_ = TRUE and security_level_id = security level id of the current user.

But instead, ActiveChildren() returns all menu items instead of the filtered set. ActiveChildren populates an array in the following static function:

public static function Tree()
{
    return static::with(implode('.', array_fill(0, 4, 'ActiveChildren')))
        ->where('menu_type', '=', 'PRT')
        ->get();
}

That is then loaded via the AppServiceProvider whenever the menu is included in a blade file:

public function boot()
{
    view()->composer('desktop.menu.parent', function ($view) {
        $items = Menu::Tree();
        $view->withItems($items);
    });
}

All this works fine, just the menu items are not filtered, any ideas?

Upvotes: 0

Views: 78

Answers (3)

C. Gill
C. Gill

Reputation: 175

After some more investigation, I have found the issue to be in my blade code.

I still referenced $item['children'] instead of $item['activechildren']

<li>{{ $item['menu_text'] }}</li>
@if (count($item['activechildren']) > 0)
    <ul>
    @foreach($item['activechildren'] as $item)
        @include('desktop.menu.children', $item)
    @endforeach
    </ul>
@endif

Why did $item['children'] still work? Why wasn't this throwing an error?

Upvotes: 0

PHP Geek
PHP Geek

Reputation: 4033

try this:

\App\model_name::where('active_',TRUE)->where('security_level_id', $securityLevel);

Upvotes: 1

Peter
Peter

Reputation: 1725

It looks like you need to update your ActiveChildren() relation:

public function ActiveChildren()
{
    $securityLevel = Auth()->User()->security_level_id;

    /* $activeChildren = Menu::Children()
     *     ->where('active_', TRUE)
     *     ->where('security_level_id', $securityLevel);
     *
     * return $activeChildren;
     */
    return $this->Children() // switch Menu::Children() to $this->Children()
        ->where('active_', TRUE)
        ->where('security_level_id', $securityLevel);
}

Upvotes: 1

Related Questions