Laravel-在所有视图之间共享数据 [英] Laravel - share data between all views

查看:199
本文介绍了Laravel-在所有视图之间共享数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Laravel 5.2版本,并且试图在所有视图之间共享数据,但是由于某些原因,我无法使其正常工作.在我的Controller.php __construct function中,我已经像这样设置了它,但这不起作用:

I am using Laravel 5.2 version, and I have tried to share data between all views, but for some reason I can't get it to work. In my Controller.php __construct function I have setup it up like this, but this is not working:

<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesResources;

class Controller extends BaseController
{
    use AuthorizesRequests, AuthorizesResources, DispatchesJobs, ValidatesRequests;

    public function __construct()
    {
        view()->share('user', Auth::user());
     }
}

我正试图在导航中像这样渲染部分内容:

I am trying to render that in my navigation partial like this:

<li>{{ $user->name }}</li>

推荐答案

您应创建服务提供商,或为此使用视图作曲家

You should create service provider or use view composers for that.

此外,您无需为Auth::user()auth()->user()创建单独的变量,因为您已经可以在所有开箱即用的视图中使用这些变量.

Also, you don't need to create separate variable for Auth::user() or auth()->user(), because you already can use those in all views out of the box.

这篇关于Laravel-在所有视图之间共享数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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