Laravel

Ways for passing data to view in Laravel
18.01.2022
img

Laravel provides different ways to pass data to a view. We can pass data directly from routes or through the controller.

1. Using view(): We can directly pass the data in the ‘view()’ helper function by using the second parameter in the function which takes an array as key and value pair.

          Route::get('/', function () {
              return view('gfg', ['articleName' => 'Article 1']);
          });
 We can pass an array with multiple values also.
                   
          Route::get('/', function () {
              return view('gfg', [ 'articles' => 
                 ['Article 1','Article 2','Article 3'] ]);
          });
2. Using with(): The ‘with()’ is a method to pass individual form of data and is used with the ‘view’ helper function.

          Route::get('/', function () {
              $articleName = ‘Article 1’;
              return view('gfg')->with('articleName', $articleName)->
                 with('articlePublished', 'On GeeksforGeeks');
          });
3. Using compact(): The ‘compact()’ is a PHP function that can be used for creating an array with variable and there value. Here the name on the variable is the key and the variable content is the value.
                    
           Route::get('/', function () {
               $articleName = ['Article 1','Article 2'];
               $articlePublished = 'On GeeksforGeeks';
               return view('gfg', compact('articleName', 
                  'articlePublished'));
           });
4. Using Controller Class: Passing data using controller class is easy and is the right way.
          
          namespace App\Http\Controllers;
          use Illuminate\Http\Request;

          class GfGController extends Controller
          {
	    public function article() {
		return view('gfg', ['article' => 'Passing Data to View']);
	    }
          }

Source: geeksforgeeks.org

back to all posts