Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to exclude certain views with laravel view composer

How can I make sure that I load data via view composer for select views and only exclude a few, two views to be specific? Can i use a regex instead of '*'?

public function boot()
{
    view()->composer(
        '*',
        'App\Http\ViewComposers\ProfileComposer'
    );
}

There are just two views i'd like to avoid, they extend the same blade used by others, not sure declaring all the 99 others would be the best - if i can just define the ones to be left out that'd be great.

like image 427
Chiko Avatar asked Jul 26 '16 00:07

Chiko


1 Answers

Perhaps it is not the best way for doing this but it can do like this

In your services provider register your view composer

public function boot()
{
    view()->composer(
        '*',
        'App\Http\ViewComposers\ProfileComposer'
    );
}

In Your ProfileComposer compose method View class repository is type hinted. Use it to get the name of the current name of the view and make a condition for excluded view name.

class ProfileComposer
{


    public function __construct()
    {
        // Dependencies automatically resolved by service container...
    }

    /**
     * Bind data to the view.
     *
     * @param  View  $view
     * @return void
     */
    public function compose(View $view)
    {
        $excludedViews = ['firstView','SecondView'];

        //Check if current view is not in excludedViews array
        if(!in_array($view->getName() , $excludedViews))
        {
             $view->with('dataName', $this->data);
        }
    }
}
like image 114
sunny kashyap Avatar answered Sep 24 '22 18:09

sunny kashyap