Reputation: 31323
I'm just starting to learn Laravel and I'm having a small issue regarding passing values across files.
In the Routes file, I have the following function.
Route::get('/', function()
{
$data = [
'first_name' => 'Jane',
'last_name' => 'Doe',
'email' => '[email protected]',
'location' => 'London'];
return View::make('hello')->with($data);
});
I'm passing the $data
array to a file named hello.blade.php. And I want to print out all the values in this array. The problem is I can't iterate through them and output the values in it. I get the error Undefined variable: data.
Here's my blade file.
@extends('layouts.main')
@section('content')
@foreach ($data as $item)
<li>{{{ $item }}}</li>
@endforeach
@stop
I learned that I could do something like this return View::make('hello')->withData($data);
in the Route file and get it working. But I don't like the way of appending a variable name like withData
.
Is there a way to pass the array variable and access it from the blade file?
Thank you.
Upvotes: 2
Views: 10703
Reputation: 1418
Quasdunk is total right. if you are pass an array to the blade.
then you need to use foreach to loop the data like: in your blade, you can dd($data). in my case , my return datas in the blade is:
array:1 [▼
0 => {#185 ▼
+"id": 1
+"title": "Alice."
+"artist": "Lysanne Lang Sr."
+"rating": 0
+"album_id": 3
+"created_at": "2021-02-03 23:24:05"
+"updated_at": "2021-02-03 23:24:05"
}
]
So you need below to display the datas value.
@foreach($data as $data_value)
{{$data_value->title}}
@endforeach
Upvotes: 0
Reputation: 15230
You're passing a single argument that is an associative array, this tells Blade: Hey, take the keys of this array as names of variables and make their value corresponding to the key's value in the array.
That means, you now have in your view a variable $first_name
with the value of 'Jane', a variable $last_name
with the value of 'Doe' and so on.
This would be the same as doing
return View::make('hello')
->with('first_name', 'Jane')
->with('last_name', 'Doe');
You get the idea.
If you want to pass the array itself, you have to tell blade: Hey, take this array and make it available in the view by the given name:
return View::make('hello')->with('data', $data);
Now you have the whole array available in your view by the variable $data
.
Upvotes: 8