Laravel Fundamentals - Passing Variables from the Controller to View

  • June 02, 2015

Welcome to the incredibly popular Easy Laravel 5 companion blog. To celebrate the new edition's release (updated for Laravel 5.5!) use the discount code easteregg to receive 20% off the book or book/video package! » Buy the book

Your views will typically include dynamic data created within a corresponding controller action. If you're new to Laravel it might not be so apparent how to go about passing this data into the view and rendering it at the desired location. In this post I'll show you how.

Suppose you wanted to pass the name of a list into the home page view. Open the Welcome controller (app/Http/Controllers/WelcomeController.php) and corresponding view (resources/views/welcome.blade.php). Modify the Welcome controller's index action to look like this:

public function index()      
{ 
  return view('welcome')->with('name', 'San Juan Vacation');
}

Save these changes and then open welcome.blade.php (resources/views), and add the following line anywhere within the file:

@
<p>{{ $name }}</p>

Reload the home page and you should see San Juan Vacation embedded into the view! As an added bonus, I included an example of a Blade comment (Blade comments are enclosed within the @ tags).

You can also use a cool shortcut known as a magic method to identify the variable name:

public function index()      
{ 
    $name = 'San Juan Vacation';
    return view('welcome')->withName($name);
}

This variable is then made available to the view just as before:

<p>{{ $name }}</p>

You can use the with method to pass multiple variables into a view. Just pass along an associative array, as demonstrated here:

public function index()
{

    $data = array('name' => 'San Juan',
                  'date' => date('Y-m-d'));  

    return view('welcome')->with($data);

}

To view both the $name and $date variables within the view, update your view to include the following:

You last visited {{ $name }} on {{ $date }}.

You could also use multiple with methods, like so:

return view('welcome')
  ->with('name', 'San Juan Vacation')
  ->with('date', date('Y-m-d'));

This approach can get messy if you needed to pass along more than two variables. Save some typing and your eyesight using PHP's compact() function:

$name = 'San Juan Vacation';
$date = date('Y-m-d');
return view('welcome', compact('name', 'date'));

The $name and $date variables defined in your action will automatically be made available to the view. See the compact() function documentation at http://php.net/compact for more information.