I'm showing a variable in my layout file app.blade.php. That variable has a default value defined in my global 'view composer'. I need to overwrite that value from within a controller method, how can I do that?
2 Answers
That's a tricky one. The problem is that the view composer gets trigger after the controller has returned the view. However you can check inside the view composer if the value has been set:
public function compose(View $view)
{
if(!$view->offsetExists('foo')){
$view->with('foo', 'default');
}
}
And when you want to "override" the default in your controller:
return view('view.name')->with('foo', 'bar');
Comments
In your controller you may use something like this:
$view = view('view.name')->with(...); // This will trigger the composer
This will return the rendered (composer ran already) View then you may set the value into the variable using something like this:
$view->variablename = 'value'; // You may also check it using $view->offsetExists(...)
Then return the view like:
return $view;
1 Comment
Agu Dondo
Looks like the composer is still running after and overwritting the values
view()->share('variable', value)in your controller?