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?
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With