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

查看:100
本文介绍了无法在控制器的构造函数上调用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.

作为替代,您可以直接定义基于Closure的中间件 在控制器的构造函数中.使用此功能之前,请确保 您的应用程序正在运行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 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类来验证用户身份 在您的控制器操作上:

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

    //
}

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

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