Pass data from controller to view laravel 5 :-
Sometimes we need to pass data from controller to view in laravel 5 like working with database query, select option and more. it’s simple and easy with built in function in laravel 5. We can send data from controller to view easily with with() in laravel. Also there are more way to send or pass data to view from controller. I am describing some easy way how to pass data form controller to view in laravel 5.
1. Passing an array :-
$data = array(
'name' => 'Rakesh',
'email' => 'sharmarakesh395@gmail.com'
);
return View::make('user')->with('data', $data);
//Accesing $data on view :-
{!!$data!!}
{!!$data['email']!!}
2. Working with query :- with with()
function view() {
$q = Model::where('name', '=', 'Foo')->first();
$users = Model::order_by('list_order', 'ASC')->get();
return $view->with('users', $users)->with('q', $q);
}
//Accesing on view :-
{!! $q->name !!}
with compact() :-
function view() {
$q = Model::where('name', '=', 'Foo')->first();
$users = Model::order_by('list_order', 'ASC')->get();
return $view->with('users', compact('q','users'));
}
3. Passing select options :-
public function oplist(){
$options="";
for($i=1;$i<10;$i++) {
$options.="<option value=".$i.">".$i."</option>";
}
return View::make('viewname')->with('options',$options);
}
//Accessing on view :-
<select>{!!$options!!}</select>
Above code works with view::make() now we will see pass data from controller to view on redirect. it’s also easy to pass data on redirect in laravel. Let’s see how to pass data from controller on redirect.
1. Redirect with flash data :-
return Redirect::to('user/login')->with('message', 'Login Failed');
2. Redirect to named route with data :-
return Redirect::route('profile', array('user' => 1));