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条)

报告相同问题?

悬赏问题

  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集