We Are A Web Agency With A Passion For Design.

Various ways for passing data to view in Laravel

Laravel provides different ways to pass data to a view. There are various ways of passing data to views:

  1. Using view()
  2. Using with()
  3. Using compact()
  4. Using Controller Class

1] Using view()

As view() method requires two parameters to be passed. Array of data is passed as a second parameter to view() method.

Write this below code in the ‘web.php’ file.

Route::get('/', function () { 
return view('student', ['studentName' => 'Anisha']); 
});

In view(), the first parameter is the name of the view
and the second parameter is where we have to specify the
key and value pair of the data.

2] Using with()

We can also use the with() function to pass the data to views. The ‘with()’ is a method to pass individual form of data and is used with the ‘view’ helper function. The ‘with()’ function contains two parameters,name of variable and value of that variable.

Write this below code in the ‘web.php’ file.

Route::get('/', function () {
   $studentName = ‘Asha’;
   return view('student')->with('studentName', $studentName);
});

3] Using compact()

The compact() function is also used to pass the data to views. It is a PHP function. It used to create an array from variables and their values.

Write this below code in the ‘web.php’ file.

Route::get('/', function () {
    $studentName = ['Nikita','Bhavna'];
    $tagline = 'Are Employees'; 
return view('student', compact('studentName', 'tagline')); });

4] Using Controller Class

Passing data using controller class is simple and is the right way.

  1. We need to create a controller class by running the command below on the command line, “php artisan make:controller StudentController”
  2. After that, open the ‘StudentController.php’ file in ‘app/Http/Controllers’ directory and create a public function. In this function we can specify any of the data passing method we saw above.

Leave a Reply