Home / Snippets / How to Pass Data From Controller To Views in Laravel 8
How to Pass Data From Controller To Views in Laravel 8 cover

How to Pass Data From Controller To Views in Laravel 8

646

3 years ago

0 comments

There are 5 different ways to pass data from controller to blade views and depending on your chosen preference, you can pick whichever goes well with your code.

For the sake of the example, the views will be returned from the route body but in your case, it will be the controller.

Pass Array of Data
The first way is to pass an array of data to the second parameter of the "view" helper method like below.
Route::get('/articles', function () {
  $articles = Article::take(8)->get();
  $extraStuff = [1, 2, 3, 4];
  
  return view('articles.index', [
    'articles' => $articles,
    'extraStuff' => $extraStuff
  ]);
});

Pass by Chaining the Data
The second way is to pass it by chaining the view helper using the "with" method. 
Route::get('/articles', function () {
  $articles = Article::take(8)->get();
  $extraStuff = [1, 2, 3, 4];

  return view('articles.index')
    ->with('articles', $articles)
    ->with('extraStuff', $extraStuff);
});

Pass by using compact
The third way is to use "compact" helper function, with this method you can just pass in the variable you want to pass on to the view as a string.
Route::get('/articles', function () {
  $articles = Article::take(8)->get();
  $extraStuff = [1, 2, 3, 4];

  return view('articles.index', compact('articles', 'extraStuff'));
});

Sharing with All Views
The fourth way is to share data with all of the views. This can be defined from the "AppServiceProvider" class and on the "boot" method. These can also be considered as a global data sources.
<?php

namespace App\Providers;

use Illuminate\Support\Facades\View;

class AppServiceProvider extends ServiceProvider
{
  public function boot()
  {
    $extraStuff = [1, 2, 3, 4];

    View::share('extraStuff', $extraStuff);
  }
}

Sharing with View Composer
The final one is to share the data through view composer. View composer can share the data between multiple views or single views depending on your preference.

The place you register/define it is in the service provider boot method. In the case of below, the data will only be shared on the dashboard page. if you want to share it for all views, you can specify it as wildcard "*".
public function boot()
{
  // Using closure based composers...
  View::composer('dashboard', function ($view) {
    $extraStuff = [1, 2, 3, 4];

    $view->with('extraStuff', $extraStuff);
  });
}

notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

If you like our tutorial, support us by being our Patreon or buy us some coffee ☕️

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this