Ad

Laravel: Pass Current View Name To View Composer

- 1 answer

I have a blade file in Laravel, called products.blade.php. Inside of that file, I'm including a sub-view, which displays data from the database. The sub-view is fetching the data using a View Composer (to avoid writing the same code everywhere I need to display that data).

Is it possible to pass the name of the "main" view to that View Composer?

In my AppServiceProvider I have this code:

    view()->composer('*', function ($view) {
        view()->share('view_name', $view->getName());
    });

So the sub-view knows the name of the parent view. I've tried:

@include('sub-view.name', ['parent' => $view_name])

and tried to access that parent variable in the View Composer but I get: Undefined variable: parent.

I've also tried $view->getName() in the compose method of the View Composer, however it gives me the name of the sub-view and I need the parent.

Any help would be appreciated.

Thanks in advance

Ad

Answer

All the view data is accessible by using $view->getData() method.

So in the view composer you can do

class MyCustomComposer
{
    /**
     * Bind data to the view.
     *
     * @param  View  $view
     * @return void
     */
    public function compose(View $view)
    {
        $currentView = $view->getData()['view_name'];

        // Do something
    }
}
Ad
source: stackoverflow.com
Ad