Laravel - Pass more than one variable to view
I have this site and one of its pages creates a simple list of people from the database. I need to add one specific person to a variable I can access.
How do I modify the return $view->with('persons', $persons);
line to also pass the $ms variable to the view?
function view($view)
{
$ms = Person::where('name', 'Foo Bar');
$persons = Person::order_by('list_order', 'ASC')->get();
return $view->with('persons', $persons);
}
Just pass it as an array:
$data = [
'name' => 'Raphael',
'age' => 22,
'email' => '[email protected]'
];
return View::make('user')->with($data);
Or chain them, like @Antonio mentioned.
This is how you do it:
function view($view)
{
$ms = Person::where('name', '=', 'Foo Bar')->first();
$persons = Person::order_by('list_order', 'ASC')->get();
return $view->with('persons', $persons)->with('ms', $ms);
}
You can also use compact():
function view($view)
{
$ms = Person::where('name', '=', 'Foo Bar')->first();
$persons = Person::order_by('list_order', 'ASC')->get();
return $view->with(compact('persons', 'ms'));
}
Or do it in one line:
function view($view)
{
return $view
->with('ms', Person::where('name', '=', 'Foo Bar')->first())
->with('persons', Person::order_by('list_order', 'ASC')->get());
}
Or even send it as an array:
function view($view)
{
$ms = Person::where('name', '=', 'Foo Bar')->first();
$persons = Person::order_by('list_order', 'ASC')->get();
return $view->with('data', ['ms' => $ms, 'persons' => $persons]));
}
But, in this case, you would have to access them this way:
{{ $data['ms'] }}