I love the way of passing data to views in Laravel. But I don't use the "with" methode, I prefer to pass all my data as the second argument in the view helper function:
$data = [
'name' => Auth::User() -> name
]
return view('dashboard', $data);
Now it's very easy to use my data in the view:
Hello {{ $name }}
There's no need to do
Hello {{ $data['name'] }}
But here is my problem:
I want to do the same in a view composer. But the only way I have seen to pass data to views with view composers is this:
public function compose(View $view)
{
$data = [
'name' => Auth::User() -> name
]
$view -> with('data', $data);
}
But this requires me to do
Hello {{ $data['name'] }}
in my view, which I don't want. I want to use the short syntax. So is there a way to pass it like I described above? As second argument of the view function?
Thanks
Just step through each part of your array with a foreach
loop:
foreach($data as $key => $value) { $view->with($key, $value); }
In answer to your question about just calling the view
function an passing values, the answer is no, you can't do it that way.
Think about what you're doing in your first example. When you call view('template', $data)
, you're calling a helper function defined in the Laravel core. What is that function doing? It's instantiating a view, probably by calling View::make()->with()
. In other words, behind the scenes it's doing the thing you want to avoid.
Now how would that work with a view composer? I imagine it would go something like this:
In your controller, you call view('template', $somedata)
.
You now have a view object with $somedata
included.
On the way to rendering the HTML page, Laravel calls your view composer, passing along the view object you created a moment ago.
Then you call view($newdata)
(or something like that - I'm not clear on what the syntax would be) and it would attach the new data to the existing view object. But this is not something that the Laravel developers have done. That's not to say it couldn't be done, it is just not a use case that they considered.
What you can do is step through your new data in the view composer and add the individual values to the existing view, like this:
foreach ($newdata as $key => $value) {
$view->with($key, $value);
}