vendredi 29 septembre 2017

Laravel View Composer dublicating SQL queries for every view

So 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?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2woiFun
via IFTTT

Aucun commentaire:

Enregistrer un commentaire