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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39175252/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 14:22:11  来源:igfitidea点击:

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

laravellaravel-5.3

提问by Daniel

I'm trying to check if the user has permission to a certain model. Up until now (with Laravel 5.2), I added this code at the constructor:

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

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

Now, after upgrading to Laravel 5.3, Auth::user()returns nullwhen being called from the controller's constructor. If I call it within any other method of the class, it returns the currently logged in user.

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

Any Ideas why?

任何想法为什么?

回答by Samsquanch

See 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');

    //
}

构造函数中的会话

在以前版本的 Laravel 中,您可以在控制器的构造函数中访问会话变量或经过身份验证的用户。这从未打算成为该框架的显式特征。在 Laravel 5.3 中,您无法在控制器的构造函数中访问会话或经过身份验证的用户,因为中间件尚未运行。

作为替代方案,您可以直接在控制器的构造函数中定义基于闭包的中间件。在使用此功能之前,请确保您的应用程序运行的是 Laravel 5.3.4 或更高版本:

<?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);
        });
    }
}

当然,您也可以通过在控制器操作上键入 Illuminate\Http\Request 类来访问请求会话数据或经过身份验证的用户:

/**
 * 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');

    //
}

回答by kjdion84

Because you're attempting to access the instance before the middleware even fires. You can use request()->user()instead.

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

回答by Huynh Thai Hung

class StudentController extends Controller
{

    public $role;

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

Hope help you!!!

希望能帮到你!!!

Update: Get your code inside

更新:获取您的代码

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