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.如果我在类的任何其他方法中调用它,它将返回当前登录的用户.

Any Ideas why?

推荐答案

请参见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.

作为替代方案,您可以直接定义基于闭包的中间件

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

当然,您也可以访问请求会话数据或

/**
 * 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硬编码字符串(还有 1 个错误)..(验证异常类)

如何在 laravel 中为另一个用户 session()->forget('cart')?

如何获得每种类型的总和

未捕获的 TypeError:Vue.component 不是函数

Laravel 错误ReflectionException-类 App\Http\Kernel 不存在

验证规则 required_if 与其他条件(Laravel 5.4)

Carbon(laravel)处理无效日期

如何在 NetBeans 中添加带有点 (blade.php) 的自定义文件扩展名?

Laravel 5 - 仅在特定页面/控制器(页面特定assets资源)上添加样式表

限制 Blade foreach 循环中的结果

链接到容器时如何使用主机网络?

控制器中的 Laravel Auth 用户 ID

找不到列:1054字段列表中的未知列0-Laravel-我的代码中的任何地方都没有0列

如何处理 laravel 5 中的私有图像?

Laravel 动作未定义

laravel:Eloquent的例子将数据插入数据库

Laravel:方法[显示]不存在

如果 Laravel 中的值不为空,如何验证输入字段

Laravel 5 - 判断日期是否是今天

如何访问 Laravel 集合中的第 n 个项目?