Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel View Composer duplicating SQL queries for every view

I need to access some data (User details) in most views. What I have done:

I created ComposerServiceProvider

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class ComposerServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        view()->composer(
            ['includes.header','profile'],
            'App\Http\ViewComposers\CustomerComposer'
        );

    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

Created CustomerComposer class

<?php

namespace App\Http\ViewComposers;

use Illuminate\Support\Facades\Auth;
use Illuminate\View\View;
use Modules\Customers\Entities\CustomerDetail;

class CustomerComposer
{
    public $customer = [];

    /**
     * Bind data to the view.
     *
     * @param  View  $view
     * @return void
     */
    public function compose(View $view)
    {
        $user = Auth::guard('customer');

        $this->customer = CustomerDetail::where('user_id',$user->id())->first();

        $view->with( 'customer', $this->customer );
    }
}

Everything works but when I look at Debug bar it shows me same queries excecuted per view, so for example if I define ['includes.header','profile'] Same SQL will be excecuted twice if ['includes.header','profile','something_else'] 3 times and so on...

In this case query's is

select * from `customer_details` where `user_id` = '1' limit 1
select * from `customer_details` where `user_id` = '1' limit 1

If I provide wildcard in

view()->composer(
            ['*'],
            'App\Http\ViewComposers\CustomerComposer'
        );

It will generate 23 queries! I missed something here?

like image 669
RomkaLTU Avatar asked Sep 29 '17 18:09

RomkaLTU


1 Answers

Ok I think I found solution. In ComposerServiceProvider class:

/**
* Register the application services.
*
* @return void
*/
public function register()
{
    $this->app->singleton(\App\Http\ViewComposers\CustomerComposer::class);
}

That it.

In Laravel Docs

Registering A Singleton

Sometimes, you may wish to bind something into the container that should only be resolved once, and the same instance should be returned on subsequent calls into the container:

like image 61
RomkaLTU Avatar answered Sep 28 '22 20:09

RomkaLTU