Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

kaiserkais's avatar

duplicated query

i have in my front end template two menus, one for mobile and another for desktop, I have foreach loop for every menu with the categories, is there a way to not use the query two times ? "for better speed loading"

0 likes
1 reply
MichalOravec's avatar
Level 75

You can use view composer as a singleton. Then your query will be fetch only once.

<?php

namespace App\Http\View\Composers;

use App\Category;
use Illuminate\View\View;

class MenuComposer
{
    protected $categories;

    public function compose(View $view)
    {
        if (! $this->categories) {
            $this->categories = Category::all();
        }

        $view->with([
            'categories' => $this->categories
        ]);
    }
}
<?php

namespace App\Providers;

use App\Http\View\Composers\MenuComposer;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;

class ViewServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton(MenuComposer::class);
    }

    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
        View::composer([
            'view.where.you.use.that.categories',
            'another.one'
        ], MenuComposer::class);
    }
}

Docs: https://laravel.com/docs/7.x/views#view-composers

Please or to participate in this conversation.