Let say we have something like this in a AppServiceProvider
$page = [
'title' => 'Page Name',
'info' => 'Content Here'
];
view()->share('page', $page);
In view:
<h1>{{$page['title']}}</h1>
<p>{{$page['info']}}</p>
If I want to overwrite $page['title']
in method controller, I have tried like this:
public function index()
{
$page['title'] = "overwrite title only";
return view('index', compact('page'));
}
Problem is $page['info']
will not longer be available, it will not exist in view. How can I overcome this situation?
The simplest solution could be to replace in your Controller:
$page['title'] = "overwrite title only";
with:
$page = array_merge(
view()->shared('page'),
['title' => "overwrite title only"]
);
view()->shared()
method returns the shared variable, then we can override some array elements and pass the overridden array to the view.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With