我正在处理一个项目,该项目有一个带有顶栏的控制面板,该顶栏包含有关用户的详细信息,如用户名、电子邮件、图像url等。该顶栏几乎在所有控制面板视图上运行。现在,在每个控制面板控制器中,我都会做一些类似的事情
/***** PostController *********/
class PostController extends Controller
{
protected $user;
public function __construct()
{
$user = Auth::user(); // Note: here $user is not a global variable
$this->user['user_name'] = $user->name;
$this->user['user_email'] = $user->email;
$this->user['user_role'] = $user->getRolesName()->first();
$this->user['user_image'] = $user->image;
}
然后在索引控制器中,我会将角色传递给当前用户,并发布这样的详细信息。
public function index()
{
$user = $this->user;
$posts = json_decode( Post::with('author')->get()->toJson() );
return view('globaladmin.posts.viewposts',compact('posts'), $user);
}
我认为可能有一种更好的方法来做这件事(也许是一个类似存储库的设计模式),就像往常一样,任何帮助都将不胜感激。
您可以使用一种称为视图共享的东西。如果您查看文档(http://laravel.com/docs/master/views#sharing-所有视图的数据),您将能够创建一个服务提供商,您可以将代码放入其中。
一个快速(可能是肮脏的)修复方法是使用app''Http''Controllers''Controller.php,如下所示:
public function __construct()
{
$user = Auth::user(); // Note: here $user is not a global variable
$global_user = [];
if ($user !== null) {
$global_user['user_name'] = $user->name;
$global_user['user_email'] = $user->email;
$global_user['user_role'] = $user->getRolesName()->first();
$global_user['user_image'] = $user->image;
}
view()->share('global_user', $global_user);
}
编辑:要在刀片中使用这个,类似的东西会起作用:
@if($global_user)
{!! $global_user->user_name !!}
@endif
由于您有简单的数据要共享,我建议您使用服务注入,只需将此代码片段添加到您的主刀片模板:
@inject('user', 'App'User')
然后在每个扩展主模板的模板中使用$user
:
<div>
Username: {{ $user->user_name }}.
...etc
</div>
顺便说一句:你不必分享这个,因为在auth()
全局功能中,你可以访问你当前登录的用户,比如:
auth()->user()->name // or ->email maybe!