Passing data to views from routes in Laravel.

There are multiple ways through which you can pass data from your routes to views. We will explore them all.

  • Attaching data to view

You can bind your data directly to your view file and while returning the view from the routes.

Route::get('/', function(){
   return view('welcome',['name'=>'World','age'=>3]); 
});

With this above route, variable name and age are now directly available to your in your view file and you can echo / print the variable with something like

<h1>Hello {{$name}}</h1>
  • Attaching data using with method

You can bind data to view using with keyword. This works exactly similar to the previous way of attaching the data.

Route::get('/', function(){
   return view('welcome')->with('name','World'); 
});
  • Using compact method

Laravel has provided a compact method which looks more systematic and can be used like below.

//Welcome view
Route::get('/', function(){
    $name = 'World';
    return view('welcome',compact('name')); 
});

//Data View
Route::get('/data', function(){
    $name = 'World';
    $age = '28';
    return view('data',compact('name','age')); 
});

//Sending as List
Route::get('/listdata', function(){
    $tasks = [
        'Write Code',
        'Unit Test',
        'Deliver'  
    ];
    return view('listdata',compact('tasks')); 
});

 

tgugnani: Web Stuff Enthusiast.