Aslam H
Aslam H

Reputation: 1801

How to prevent loops in laravel global variable

I've created file GlobalVariable.php inside app\Composers

public function compose($view)
{
    $categories = \App\Models\Category::all();
    $view->with('globCategory', $categories);
}

then register to AppServiceProvider the code view()->composer('*', GlobalVariable::class);

I use global $globCategory for creating dynamic navbar

<ul class="nav nav-tabs border-0 flex-column flex-lg-row">
    @foreach ($globCategory as $item)
        <li class="nav-item">
            <a href="{{ route('deal.category', ['category' => $item->slug]) }}" class="nav-link">{{$item->name}}</a>
        </li>
    @endforeach
</ul>

the only problem here when I see laravel debuggar it show repetition of categories query.

here is the result

enter image description here

How to avoid this looping query? is there correct way?

Upvotes: 0

Views: 83

Answers (2)

GTCrais
GTCrais

Reputation: 2087

The way you're registering your view composer (using '*' instead of a particular view name), it's going to call the compose method for every single rendered view + subview.

What you can do is instead of this:

view()->composer('*', GlobalVariable::class);

Have this:

\View::share('globCategory', \App\Models\Category::all());

This will globally share your categories (within views), and run the query only once.

Upvotes: 1

Harpal Singh
Harpal Singh

Reputation: 702

View composers, as described from the laravel documentation, bind data to a view every time it is rendered. They clean our code by getting fetching data once and passing it to the view.

While it is possible to get the data in every controller method and pass it to the single view, this approach may be undesirable.

Replace the view name with an asterisk wildcard.

Upvotes: 0

Related Questions