laravel 5.4:无法在__construct方法中访问Auth :: user() [英] laravel 5.4 : cant access Auth::user() in the __construct method

查看:623
本文介绍了laravel 5.4:无法在__construct方法中访问Auth :: user()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以前的Laravel版本中,在我用来执行以下操作的所有方法中,我需要访问登录用户的控制器:

In previous versions of Laravel, in the controllers which I needed to access logged user in all the methods I used to do something like this:

class DashboardController extends Controller
{
    private $user ;
    function __construct(Request $request)
    {
        $this->middleware('auth');
        $this->user = \Auth::user();
    }

    function func_1(){
      $objects = Objects::where('user_id' , $this->user->id )->get();
    }
    function func_2(){
      $objects = Objects::where('user_id' , $this->user->id )->get();
    }
    function func_3(){
      $objects = Objects::where('user_id' , $this->user->id )->get();
    }

主要是因为我不喜欢默认语法\Auth::user(),但是升级到5.4后,它不再起作用,我从$this->user

Mostly because I don't like the default syntax \Auth::user() but after upgrading to 5.4 this doesn't work anymore and I get null from $this->user

尽管如此,它在其他方法中也能正常工作.基本上\Auth::user()__construct方法中返回null,但在其他函数中工作正常.

It works fine in other methods though. Basically \Auth::user() return null in the __construct method but works fine in the other functions.

推荐答案

作为

在以前的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.

所以尝试一下:

public function __construct()
{
    $this->middleware('auth');
    $this->middleware(function ($request, $next) {
        $this->user = Auth::user();

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

这篇关于laravel 5.4:无法在__construct方法中访问Auth :: user()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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