1. Home
  2. Laravel
  3. Pass data to view

Examples of passing data to a view.

#laravel#route#view
Route::get('/', function(){
    
    // Data example
    $sections = ['Intro','Information','Stats'];

    // OPTION 1 - Pass in the second argument.
    return view('dashboard', [
        'sections' => $sections // This variable is now available in the dashboard view
        'data' => 'Some other data' // You can create multiple data holding data
    ]);

    // OPTION 2 - Using "with" magic methods.
    return view('dashboard')->withSections($sections)->withData($data);

    // OPTION 3 - Combining the two approaches above.
    return view('dashboard')->with([
        'sections' => ['Intro','Information','Stats'],
        'data' => 'Some other data'
    ]);
});
copy
Full Laravel cheatsheet