Question

I need the same menu in all my views.

So I get data I need for output the menu in a constructor defined in my BaseController.

To got the data I've first tried to use View::composer but dunno why I doesn't get any error, it looks like View::composer isn't executed at all...

If I use View::share, its work

//BaseController.php

//function called in the constructor
public function init()
{
    $envs = $this->game->environments()->get();

    View::share('test', $envs);

    View::composer('layouts.base', function($view)
    {
        $view->with('envs', $envs);
    });
}

//base.twig

//nothing output here, no error
{% for env in envs %}
         {{ env.name }}
{% endfor %}

//its work
{% for env in test %}
         {{ env.name }}
{% endfor %}

I'm new to laravel so maybe I miss something ?

Was it helpful?

Solution

I think the reason that this isn't working is because of where you put the View Composer in your code. View Composers in Laravel are essentially callbacks that are executed as soon as the view is rendered. Where is this init() function defined? My guess is that the view is being created before your view composer is defined - meaning that the view composer callback will never be executed.

Try moving the whole view composer block from the init() function and append it to the bottom of your routes.php file and see if it works. That's not a bad spot to place your view composers if you do not have too many, if you do you could create a new class to store them in and add that path to your autoload path.

Read more about view composers here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top