Can we extract an array in the laravel views?
for example consider this:
We've say 20 variables in a controller which we need to pass into blade, now of course we can pass these variables using compact like this:
return view('someview', compact('var_a', 'var_b', 'var_c', 'var_d' ....));
But is there way we can move all the variables in array and then pass it to blade and then somehow extract it in blade like this:
$data = array('var_a' => 'value', 'var_b' => 'value', 'var_c' => 'value', 'var_d' => 'value', );
return view('someview')->with($data);
then In blade access like this:
{{$var_a}} {{$var_b}} {{ $var_c}}
Like we have extract()
function in PHP, which does the same, I'm just looking for same to use in blade
I don't wan't to access as index like this:
{{ $data['var_a'] }}
I've seen and inspired by similar syntax used in opencart
yes it's simple as you can do it like so
$data = ['var1' => 'value', 'var2' => 'value'];
then
return view('someview', $data);
You can do that with several ways, I'll write 2 ways to do this
way 1:
in controller :
$data = array('var_a' => 'hello', 'var_b' => 'bye', 'var_c' => 'ok');
return view('someview', compact('data'));
then you have to use the extract()
PHP inbuilt function (See this link for more information)
Then add the following code in someview.blade.php
file:
@php
extract($data)
@endphp
<h1>{{$var_a}}</h1><br>
<h2>{{$var_b}}</h2><br>
<h3>{{$var_c}}</h3><br>
way 2:
in controller :
$data = array('var_a' => 'hello', 'var_b' => 'bye', 'var_c' => 'ok');
return view('someview', $data);
and you don't have to do anything anymore, Larval itself will do the first way.
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