Passing Multiple Variables Into A Laravel 5 View

  • March 09, 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

You'll almost certainly want to pass multiple variables into a view. In this post I'll show you several different approaches.

One way to do so involves passing them into the with method using an array:

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 snippet:

{% raw %}
You last visited {{ $name }} on {{ $date }}.
{% endraw %}

You could also use multiple with methods, like so:

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

Logically this latter approach could get rather unwieldy if you needed to pass along more than two variables. You can save some typing by 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 then automatically be made available to the view. If this is confusing see the PHP manual's compact() function documentation at http://php.net/compact.

Chapter 2 teaches you all about managing variables within your Laravel views.

Buy the book