I see, that this is still needed for 5.4+ and I just had the same problem, but none of the answers were clean enough, so I tried to accomplish the availability with ServiceProviders
. Here is what i did:
- Created the Provider
SettingsServiceProvider
php artisan make:provider SettingsServiceProvider
- Created the Model i needed (
GlobalSettings
)
php artisan make:model GlobalSettings
- Edited the generated
register
method in \App\Providers\SettingsServiceProvider
. As you can see, I retrieve my settings using the eloquent model for it with Setting::all()
.
public function register()
{
$this->app->singleton('App\GlobalSettings', function ($app) {
return new GlobalSettings(Setting::all());
});
}
- Defined some useful parameters and methods (including the constructor with the needed
Collection
parameter) in GlobalSettings
class GlobalSettings extends Model
{
protected $settings;
protected $keyValuePair;
public function __construct(Collection $settings)
{
$this->settings = $settings;
foreach ($settings as $setting){
$this->keyValuePair[$setting->key] = $setting->value;
}
}
public function has(string $key){ /* check key exists */ }
public function contains(string $key){ /* check value exists */ }
public function get(string $key){ /* get by key */ }
}
- At last I registered the provider in
config/app.php
'providers' => [
// [...]
App\Providers\SettingsServiceProvider::class
]
- After clearing the config cache with
php artisan config:cache
you can use your singleton as follows.
$foo = app(App\GlobalSettings::class);
echo $foo->has("company") ? $foo->get("company") : "Stack Exchange Inc.";
You can read more about service containers and service providers in Laravel Docs > Service Container and Laravel Docs > Service Providers.
This is my first answer and I had not much time to write it down, so the formatting ist a bit spacey, but I hope you get everything.
I forgot to include the boot
method of SettingsServiceProvider
, to make the settings variable global available in views, so here you go:
public function boot(GlobalSettings $settinsInstance)
{
View::share('globalsettings', $settinsInstance);
}
Before the boot methods are called all providers have been registered, so we can just use our GlobalSettings
instance as parameter, so it can be injected by Laravel.
In blade template:
{{ $globalsettings->get("company") }}