I'm currently developing a Web Application using Laravel 5.2, in the database I have some configurations saved, I use that Settings along a lot of controllers in the application, so I don't want to be consulting over and over again the same thing. I want to consult it only on application boot, and it this way also reduce the code and no be repetitive. I read this but it seems like are old answers to old versions of the framework. So, In Laravel 5.2 how can I do it?
2 Answers
In the given link in your question, there the answers were given for Laravel 4.x and if you want to implement the same technique in version 5.2 and later then you can use a global middleware. To do that, just create a middleware from your terminal using something like the following:
php artisan make:middleware GlobalConfigMiddleware
This'll create a middleware (GlobalConfigMiddleware.php
) in your app/Http/Middleware
directory. In this file, all you need to implement the logic for setting up the config within the handle
method which should look something like the following:
public function handle($request, Closure $next)
{
// Pseudo Code
app()->singleton('site_settings', function($app) {
// Imagine you have the Setting Eloquent Model
// Get all settings using the Setting model
return \App\Setting::all();
});
// If you use this line of code then it'll be available in any view
// as $site_settings but you may also use app('site_settings') as well
view()->share('site_settings', app('site_settings'));
return $next($request);
}
Then, add this middleware class in the $middleware
property of your app/Http/Kernel.php
class, for example:
protected $middleware = [
// ...
\App\Http\Middleware\GlobalConfigMiddleware::class,
];
Now, you can use the config like this:
$site_settings = app('site_settings');
Learn about Middleware and Binding. Also remember that, this could be done in different ways.
You can use the config
helper and set some custom config variable
Set a config var
config(['app.yourvar' => 'IlikeCookies']);
Get a config var
$value = config('app.yourvar', 'fallback');
If you want it to run on boot, you can use a ServiceProvider
and fill the config in the boot() function.

- 8,864
- 6
- 44
- 85
-
ok, and where should I load the value of that variable?I have all the values in the database. That seems to be used to static values – Sredny M Casanova Feb 13 '17 at 21:19