Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - how to extract an array to variables and use them in blade

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

like image 724
Shehzad Avatar asked Sep 02 '25 04:09

Shehzad


2 Answers

yes it's simple as you can do it like so

$data = ['var1' => 'value', 'var2' => 'value'];

then

return view('someview', $data);
like image 173
Bader Avatar answered Sep 04 '25 19:09

Bader


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.

like image 29
Ramin eghbalian Avatar answered Sep 04 '25 20:09

Ramin eghbalian