Home > other >  Laravel Compact()
Laravel Compact()

Time:06-19

I have an interesting question, about compact in PHP and compact in Laravel.

Take this example in compact in PHP:

$banana = "yellow";
$apple = "red";
$result = compact('banana','apple');
var_dump($result);
//Output  
array(2) {
["banana"]=>
string(6) "yellow"
["apple"]=>
string(3) "red"
}

But when I use compact on controller in laravel to return to view, it return in variable not in array

public function fruisColor($banana="yellow",$apple="red"){
  return view('template.fruits',compact('banana','apple'));
}

But when I get this variable in template blade, it is not an array it is a variable, look:

P1 = {{ $banana }} e P1 = {{ $apple }}

If PHP compact convert to variables to array, why in template blade it is returning just var? It is not should be:

P1 = {{ $banana[0] }} e P1 = {{ $apple[0] }}

Seems confusing no?

CodePudding user response:

Since the two-argument of view method accepts an array that, according to the documentation, converts it to a variable that you can use in the blade template, Laravel can handle the array returned from the compact.

CodePudding user response:

It just the way Laravel view templates handles array;

Laravel view template handle the array and makes it possible to call your data with the array key.

It does not mean it was not passed as an array with the use of compact. Your solution could also work like this

 // In view
 Hello, {{ $banana }} {{$apple}}

//controller
 public function fruisColor($banana="yellow",$apple="red"){
   return view('template.fruits',['banana'=>"yellow", 'apple' => "red" ]);
}
  • Related