3

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?

I'll-Be-Back
  • 10,530
  • 37
  • 110
  • 213

1 Answers1

2

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.

Limon Monte
  • 52,539
  • 45
  • 182
  • 213