Laravel 5.3向数据库查询并传递所有视图 [英] Laravel 5.3 make a query to database and pass it all views

查看:79
本文介绍了Laravel 5.3向数据库查询并传递所有视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些要从数据库中获取的动态数据,并将其传递给所有视图.我试图从互联网上举一些例子,但是在我这样的情况下,它们似乎不起作用

I have a some dynamic data that I want to fetch from database and pass it to all views. I tried to make some examples from internet but they seems to be not working in my situation like

public function boot(){}

我无法进行数据库查询的

只传递硬编码的值.我尝试过的另一种方法是基本控制器,但是访问变量

to which I can't make a database query only pass hardcoded values. Another method I have tried is a base controller but the view gives me error when accessing the variable

$query = DB::table('users')->first();
\View::share('user', $query);

任何人都有基于BaseController的解决方案将不胜感激,如果我错过了什么,请提醒我

Anyone have a BaseController based solution will be appreciated and if I missed something please do remind me

推荐答案

根据

有时,您可能需要与应用程序呈现的所有视图共享一条数据.您可以使用View Facade的share方法来实现.通常,您应该在服务提供商的启动方法中发出要共享的调用.

Occasionally, you may need to share a piece of data with all views that are rendered by your application. You may do so using the view facade's share method. Typically, you should place calls to share within a service provider's boot method.

以该站点为例,您应将其添加到您的服务提供商之一:

Again as an example in that site you should add this to one of your service providers:

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        if (!app()->runningInConsole()) {
            $query = DB::table('users')->first();
            \View::share('user', $query);
        }
    }
}

这篇关于Laravel 5.3向数据库查询并传递所有视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆