在Laravel中,我有一个表设置,我从BaseController中的表中获取了完整的数据,如下所示

public function __construct() 
{
    // Fetch the Site Settings object
    $site_settings = Setting::all();
    View::share('site_settings', $site_settings);
}

Now i want to access $site_settings. in all other controllers and views so that i don't need to write the same code again and again, so anybody please tell me the solution or any other way so i can fetch the data from the table once and use it in all controllers and view.

推荐答案

At first, a config file is appropriate for this kind of things but you may also use another approach, which is as given below (Laravel - 4):

// You can keep this in your filters.php file
App::before(function($request) {
    App::singleton('site_settings', function(){
        return 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'));
});

To get the same data in any controller you may use:

$site_settings = app('site_settings');

有很多种方法,只是用一种或另一种,你更喜欢哪一种,但我用的是Container.

Laravel相关问答推荐

子目录中具有Vue实例的Laravel不起作用

Laravel mail send Amazon SES不再支持TLS 1.0和TLS 1.1连接

laravel如何在Blade 模板中将元素添加到数组

无法使用 Dompdf Laravel 9 加载图像

阻止用户查看其他用户正在查看的内容的最佳方法是什么?

在部署到 AWS 时保持我的环境参数安全

Laravel:如何在 laravel 查询生成器中使用派生表/子查询

如何通过一个 laravel 安装处理子域

带有 Laravel Passport 的 SSO

在 laravel 中更改时区

PHP 中的 Http 响应代码枚举

Laravel - 自定义时间戳列名称

Laravel 5 干预中的图像验证

Laravel 5 Mime 验证

如何调试 Laravel 框架?

如何在不使用视图的情况下使用 Laravel 4 发送Electron邮件?

Laravel 表:只能有一个自动列,并且必须定义为键

Laravel 在域和子域中共享 cookie 检测问题

Laravel 5 - 跳过迁移

在laravel中删除确认