5

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?

1
  • 2
    Have you tried with view()->share('variable', value) in your controller? Commented Feb 9, 2015 at 21:36

2 Answers 2

2

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');
Sign up to request clarification or add additional context in comments.

Comments

0

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

Looks like the composer is still running after and overwritting the values

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.