How to Pass Data to All Views in Laravel


How to Pass Data to All Views in Laravel

In this tutorial, you will learn how to pass data to all views in Laravel. This is a very important feature and also very easy to implement. Actually, the most common way we pass dynamic data to Laravel blade is to write the logic in the controller and send data to blade with the help of compact() method. However, this takes much time. In some cases, we can not pass data to every blade. To get rid of this, we will use another trick that will help you to pass data to every view in Laravel by using a single controller logic.

Also read, how to display PDF file in Laravel from public folder

Steps to Pass Data to All Views in Laravel

  1. Go to app/Providers/AppServiceProvider.php and add the below line after namespace.
use Illuminate\Support\Facades\View;

2. Now, inside the boot() method of the AppServiceProvider.php, create the data you want to display to all views in Laravel as shown below

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use DB;
use Illuminate\Support\Facades\View;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
        $categories=DB::table('categories')->get();
        View::share('categories',$categories);  
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

On the above code, you can use $data instead of $categories as shown below

View::share('data',$data);

where $data is a dynamic variable

Conclusion:- I hope this tutorial will help you to understand the overview. If there is any doubt then please leave a comment below.


Leave a Comment