Laravel-在所有视图之间共享数据 [英] Laravel - share data between all views
问题描述
我正在使用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屋!