How to pass variable to Laravel view


Passing parameter/variable to the view in laravel is something easy to do, in this article i will show you how to pass parameter/variable to the view in laravel.

Normally you call for a view using 'View' class and calling the 'make' static method, just like this:
return View::make('home');

So how to pass parameter/variable to the view? there are two ways of doing it, first is by adding second parameter to the 'make' method, and the second is using 'with' statement.

Passing second parameter to the View::make()
$data['id'] = 1000;
return View::make('info', $data);
Note the second parameter must be an array, otherwise it will show error.

On the view, you just use variable called $id, like this:
echo $id;
You can also send multiple data like this:
$data['id'] = 1000;
$data['name'] = 'John';
return View::make('info', $data);


Using 'with' statement
return View::make('info')->with('id', 1000);
Send multiple data:
return View::make('info')
	          ->with('id', 1000)
		  ->with('name', 'John');
You can also combined them both:
$data['food'] = 'pizza';
$data['drink'] = 'beer';
return View::make('info', $data)
	          ->with('id', 1000)
		  ->with('name', 'John');

Remember, if you use blade template, you can just echo like this:
{{ $id }}
{{ $name }}
{{ $food }}
{{ $drink }}

1 comments:

how much variable I can pass with view() funct


EmoticonEmoticon