jcadima
3/22/2019 - 3:36 PM

Global View Fields


https://stackoverflow.com/questions/28608527/how-to-pass-data-to-all-views-in-laravel-5
<?php
// 1) create a new service provider
// php artisan make:provider GlobalSettingsProvider

namespace App\Providers;

use App\Setting ;
use Illuminate\Support\ServiceProvider;

class GlobalSettingsProvider extends ServiceProvider
{
    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
        view()->composer('*', function ($view)
        {
            $settings = Setting::first() ;

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


2) add it to config/app.php

    /*
    |--------------------------------------------------------------------------
    | Autoloaded Service Providers
    |--------------------------------------------------------------------------
    |
    | The service providers listed here will be automatically loaded on the
    | request to your application. Feel free to add your own services to
    | this array to grant expanded functionality to your applications.
    |
    */

    'providers' => [

        /*
         * Laravel Framework Service Providers...
         */
        Illuminate\Auth\AuthServiceProvider::class,
        Illuminate\View\ViewServiceProvider::class,
        .
        .
        .
        // these are our 2 custom service providers
        App\Providers\BladeServiceProvider::class,
        App\Providers\GlobalSettingsProvider::class,

        /*
         * Package Service Providers...
         */

        /*
         * Application Service Providers...
         */
        App\Providers\AppServiceProvider::class,
        App\Providers\AuthServiceProvider::class,
        // App\Providers\BroadcastServiceProvider::class,
        App\Providers\EventServiceProvider::class,
        App\Providers\RouteServiceProvider::class,

    ],

// 3) now we will have access to $settings variable in header , footer and layout blade views