-
app/Http/ViewComposers/ClientHeaderComposer.php
Open in GitHub// In this class, we assign the global variables, with $view->with() // Note: there's no Artisan command like "php artisan make:composer", you need to create this class manually // in whatever folder you choose. In this case, author created app/Http/ViewComposers folder and namespace. namespace App\Http\ViewComposers; class ClientHeaderComposer { public function compose(View $view) { $clients = Client::findOrFail($view->getData()['client']['id']); $contact_info = $clients->contacts()->first(); $contact = $clients->user; $view->with('contact', $contact)->with('contact_info', $contact_info); } }
-
app/Providers/ViewComposerServiceProvider.php
Open in GitHub// We create this custom Service Provider class and assign the View Composers to the actual Views. // In this case, we're assigning the ClientHeaderComposer from the above example // to the view of resources/views/clients/show.blade.php class ViewComposerServiceProvider extends ServiceProvider { public function boot() { view()->composer( ['clients.show'], 'App\Http\ViewComposers\ClientHeaderComposer' ); // ... other view()->composer() statements } }
-
config/app.php
Open in GitHub// In this file, Laravel is registering its Service Providers, and we add our own provider to the list return [ // ... other configuration 'providers' => [ // ... other providers App\Providers\ViewComposerServiceProvider::class, ], ];
-
resources/views/clients/show.blade.php
Open in GitHub// We assigned our View Composer to clients.show View, but it has @include('partials.clientheader') inside. // That included partial Blade file also inherits all the global variables @extends('layouts.master') @section('content') <div class="row"> @include('partials.clientheader') @include('partials.userheader', ['changeUser' => true]) </div> // ... other Blade code
-
resources/views/partials/clientheader.blade.php
Open in GitHub// Here we're using our $contact_info variable from the View Composer <div class="col-md-6"> <div class="panel panel-primary contact-header-box"> <div class="panel-body"> </p> <!--Client info leftside--> <div class="contactleft"> <p class="client-name-text" aria-hidden="true" data-toggle="tooltip" title="{{ __('Contact person name') }}" data-placement="left"> {{$contact_info->name}}</p> @if($contact_info->email != "") ... @endif @if($contact_info->primary_number != "") ...