duanqiongchong0354 2017-02-13 21:08
浏览 43
已采纳

使整个Laravel 5.2应用程序可以访问变量

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条回答 默认 最新

  • dousui8263 2017-02-13 21:44
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图