Passing Variables to Master Template in laravel

Passing variables to master template can be achieved by register a service provider in laravel. Service providers are used as central place to configure your application.

The boot method in service provider allow to share variables to views.

File /app/Providers/AppServiceProvider.php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

use App\Fund;
class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
        $balance    =   Fund::groupBy('type')
                            ->selectRaw('sum(amount) as balance')
                            ->where('type', "=", 'Added Funds')
                            ->first();
        
        view()->share('total_balance', (int)$balance->balance);
    }

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

And then used it in view/layouts/master.blade.php

Balance: ${{ $total_balance }}

Read documentation about service providers
Service Providers

Author: Anees Ahmad

Anees Ahmad is a young co-founder, creative project manager and multi-talented web developer at Techstriders.