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


Global variable in Laravel controllers and views

我在 Laravel 5.2 中有一个带有身份验证的组中间件,我想要一个全局变量 $current_user必须在控制器中可直接访问并在视图中。

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

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

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

这很容易完成。您应该有一个其他控制器扩展的控制器。

app/Http/Controllers/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