Friday, February 8, 2019

How to pass data to all views in Laravel 5 | Sharing Data Between Views Using Laravel View Composers | Laravel 5.3 - Sharing $user variable in all views | Passing data to all views | View Composer to pass variable to all views | Passing $variables to multiple views

A view composer is exactly what you're looking for. A view composer allows you to tell your application do x when view y is rendered. For example when pages.buy is rendered anywhere in my application attach $articles.
The main thing is to create a service provider under "project/app/Providers" folder as below:
<?php
namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        view()->composer('*', function($view) {
            $view->with('isAdmin', true);
            $view->with('isSupervisor', false);
        });
        /* Make sure you have a view named "index.blade.ctp" in a folder
        named "customFolder" under "project/resources/views" folder.
         */
        view()->composer(array("customFolder.index"), function($view) {
            $view->with("xor", "XOR-1");
        });
    }

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

No comments:

Post a Comment