无法在控制器的构造函数上调用 Auth::user()

Can't call Auth::user() on controller's constructor

我正在尝试检查用户是否有权访问某个模型。到目前为止(Laravel 5.2),我在构造函数中添加了这段代码:

public function __construct()
{
    if (!Auth::user()->hasPermission('usergroups')) {
        abort(404);
    }
}

现在,在升级到 Laravel 5.3 之后,从控制器的构造函数调用时 Auth::user() returns null。如果我在 class 的任何其他方法中调用它,它 returns 当前登录的用户。

有什么想法吗?

here:

Session In The Constructor

In previous versions of Laravel, you could access session variables or the authenticated user in your controller's constructor. This was never intended to be an explicit feature of the framework. In Laravel 5.3, you can't access the session or authenticated user in your controller's constructor because the middleware has not run yet.

As an alternative, you may define a Closure based middleware directly in your controller's constructor. Before using this feature, make sure that your application is running Laravel 5.3.4 or above:

<?php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;

class ProjectController extends Controller
{
    /**
     * All of the current user's projects.
     */
    protected $projects;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware(function ($request, $next) {
            $this->projects = Auth::user()->projects;

            return $next($request);
        });
    }
}

Of course, you may also access the request session data or authenticated user by type-hinting the Illuminate\Http\Request class on your controller action:

/**
 * Show all of the projects for the current user.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return Response
 */
public function index(Request $request)
{
    $projects = $request->user()->projects;

    $value = $request->session()->get('key');

    //
}

因为您试图在中间件触发之前访问该实例。您可以改用 request()->user()

class StudentController extends Controller
{

    public $role;

    public function __construct()
    {
        $this->middleware(function ($request, $next) {  
        if (!Auth::user()->hasPermission('usergroups')) {
            abort(404);
        }
            return $next($request);
        });
    }
}

希望能帮到你!!!

更新: 获取您的代码

$this->middleware(function ($request, $next) {
//your code
return $next($request);
});