我是 laravel 的新手,我需要一些帮助来了解如何创建一个可以在模板内任何地方使用的全局变量。
例如,我想使用表从users
表中查询数据->leftjoin
并在配置为使用不同控制器的所有边栏选项卡模板中获取当前用户的结果。
例如。。。
$user = DB::table('users')
->leftJoin('groups', 'groups.id', '=', 'users.group')
->select('users.*, groups.*)
->whereRaw('where user.id = (current_user need help here)')
-first();
应允许使用...
@if($user->groups.name != 'Admin')
You are not admin
@endif
在所有边栏选项卡模板中...
您可以在appServiceProvider 中创建.php
public function boot()
{
$user = DB::table('users')
->leftJoin('groups', 'groups.id', '=', 'users.group')
->select('users.*, groups.*)
->whereRaw('where user.id = (current_user need help here)')
-first();
View::share('user', $user);
}
然后你可以在每个视图中使用它, 记得导入这个
use IlluminateSupportFacadesView;
use AppUser;
在 Laravel 中,我知道三种将变量共享到所有视图的方法:
- 在服务提供商的
boot
方法中使用View::share
。引导服务提供程序时为变量分配值。 - 使用视图编辑器 (
View::composer
(。在呈现模板之前为变量分配值。 - 使用视图创建器 (
View::creator
(。在启动视图对象后立即为变量分配值。
Laravel有这三种方法的文档:
- https://laravel.com/docs/master/views#sharing-data-with-all-views
- https://laravel.com/docs/master/views#view-composers