I want to share data across multiple view in a Laravel project I was working on. After a couple of search thanks to Google and Stackoverflow. I came to conclusion to use service provider
.
What are service providers?
Laravel documentation says:
Service providers are the central place of all Laravel application bootstrapping. Your own application, as well as all of Laravel's core services, are bootstrapped via service providers.
To create a service provider use the php artisan make:provider
command, in my case i want to have access to settings globally.
php artisan make:provider SettingServiceProvider
This command create a SettingServiceProvider
file located in providers
folder. The settingserviceprovider.php
contains two method register
and boot
method. In this tutorial we will be using the boot
method.
The boot method:
Laravel documentation says:
This method is called after all other service providers have been registered, meaning you have access to all other services that have been registered by the framework:
We will be using the boot method in the settingserviceprovide.php
to pass the data to all view. Laravel view
comes with the share
method, the method collect the global variable name and followed by the data you want to share globally.
/**
* Bootstrap services.
*
* @return void
*/
public function boot()
{
$settings = Settings::all();
view::share('settings', $settings);
}
How to register a service provider:
To register the service provider, you just need to add an entry to the provider's array in the config/app.php
file.
'providers' => [
/*
* Laravel Framework Service Providers...
*/
/*
*........... Previously registered service providers...
*/
App\Providers\SettingServiceProvider::class,
To use the new global data:
<p>{{ $settings['site_name'] }}</p>
Read more on Service Provider: