繁体   English   中英

Laravel控制器和视图中的全局变量

[英]Global variable in Laravel controllers and views

我在Laravel 5.2中有一个带有auth的组中间件,我希望有一个全局变量$ current_user ,它必须可以在控制器和视图中直接访问。

我不希望每次在控制器方法中都这样做:

$current_user   = Auth::user();
return view('account.view', ['current_user', $current_user]);

是否可以为经过身份验证的用户创建全局变量,这样做的最佳选择是什么?

这可以很容易地完成。 你应该有一个控制器,每个其他控制器扩展。

应用程序/ HTTP /控制器/ Controller.php这样。

<?php

namespace App\Http\Controllers;

abstract class Controller
{
    use DispatchesJobs, ValidatesRequests;

    protected $currentUser;

    public function __construct()
    {
        // Grab the logged in user if any and set it to this property.
        // All extending classes should then have access to it.
        $this->currentUser = \Auth::user();

        // Share this property with all the views in your application.
        view()->share('currentUser', $this->currentUser);
    }
}

在您的控制器中,您只需使用$this->currentUser即可访问登录用户。 在您的视图中,您只需使用$currentUser即可访问登录用户。 您只需要在该文件中执行一次,因为所有控制器都应该扩展Controller

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM