Search code examples
phparrayslaravellaravel-bladelaravel-routing

Passing an array to a blade file and accessing its values


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' => 'jane@hotmail.com',
        '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.


Solution

  • 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.