无法在控制器的构造函数上调用 Auth::user() [英] Can't call Auth::user() on controller's constructor

查看:40
本文介绍了无法在控制器的构造函数上调用 Auth::user()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

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

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

Now, after upgrading to Laravel 5.3, Auth::user() returns null when 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 版本中,您可以访问会话变量或控制器构造函数中经过身份验证的用户.这是从未打算成为框架的显式特征.在 Laravel 中5.3,因为中间件还没有运行,所以你不能在你的控制器的构造函数中访问会话或经过身份验证的用户.

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.

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

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 AppHttpControllers;

use AppUser;
use IlluminateSupportFacadesAuth;
use AppHttpControllersController;

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

当然,您也可以访问请求会话数据或通过类型提示 IlluminateHttpRequest 类来验证用户在您的控制器操作上:

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

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

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

    //
}

这篇关于无法在控制器的构造函数上调用 Auth::user()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆