Home >>Laravel Tutorial >Passing Data to Laravel Views
Check out the Views in Laravel before moving into this section.
There are Three methods in which data can be passed into the views:
As view() method requires two parameters to be passed. Array of data is passed as a second parameter to view() method.
Shown below is example of name array:Let's create names.blade.php
<html> <body> <h1> Name Array View : <br> <?php echo $n1; echo "<br>"; echo $n2; echo "<br>"; echo $n3; ?> </h1> </body> </html>
Above view displays the values n1, n2, n3 variables.
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class NameController extends Controller { public function show() { return view('names',['n1'=> 'Yanik','n2'=>'Nonu','n3'=>'Believe Master']); } }
Above controller's show() method is defined to return the view of name.blade.php
Route::get('/names', 'NameController@show');
with() function lets the controller to take the value of 'id' along with the view it is returning to display view with data.
Shown below is example of with() function:<html> <body> <h1> Student id is : <?php echo $id; ?> </body> </html>
Above code will display '$id' value
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class WithController extends Controller { public function show($id) { return view('student')->with('id',$id); } }
Above controller method show() is passed with a parameter $id which then returns the view of with.blade.php along with the value of id we passed using with() function. The 'with()' function contains two parameters,name of variable and value of that variable in this case 'id'.
Route::get('/with/{id}','WithController@show');
Compact function in comparision to with function which contains only two parameters, compact function can have multiple parameters.
Shown below is example of compact() function<html> <body> <h1>Name using compact() function is : <?php echo $n;?> </body> </html>
<php namespace App\Http\Controllers; use Illuminate\Http\Request; class CompactController extends Controller { public function show($n) { return view('student', compact('n')); } }
Route::get('/compact/{n}', 'CompactController@show');
Shown below some code as an example for multiple parameters in compact() function.
<html> <body> <h1> Compact() method Name Details : <br> <?php echo "id is :" .$id; echo "<br>"; echo "name is :" .$n; echo "<br>"; echo "password is :" .$p; ?></h1> </body> </html>
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class CompactController extends Controller { public function show($id,$n,$p) { return view('student',compact('id','n','p')); } }
Route::get('/details/{id}/{n}/{p}', 'CompactController@show');