dsvbtgo639708 2016-12-24 11:51 采纳率: 0%
浏览 157
已采纳

在Laravel 5.3中的父构造函数中访问Auth [复制]

This question already has an answer here:

Im working on an app in Laravel 5.3. I have created an AppController. I would like for all of my controllers to extend AppController so that they all share a few common properties and methods.

Given the below 2 implementations below, my intention is to set the current user to $this->user when AppController is constructed so it will be available to all controllers extending AppController.

I expect that when I call \App\Http\Controllers\User\PermissionController@test I should get my user object dumped twice. Once when AppController is initialized, and again when PermissionController@test is called.

However, inside of AppController __construct(), $this->user is always NULL while PermissionController@test dumps the user as expected.

AppController:

<?php

    namespace App\Http\Controllers\App;

    use App\Http\Controllers\Controller;

    class AppController extends Controller
    {
        /**
         * The current user when logged in
         * @var \User
         */
        protected $user;

        public function __construct()
        {
            if(\Auth::check() ) {
                $this->user = \Auth::user();
            }
            var_dump($this->user);
        }
    }

PermissionController:

<?php

    namespace App\Http\Controllers\User;

    use App\Http\Controllers\App\AppController;

    class PermissionController extends AppController
    {
        public function test()
        {
            if(\Auth::check() ) {
                // Do something
                $this->user = \Auth::user() ;
            }
            var_dump($this->user);
        } 
    }

If it matters, I'm using https://github.com/Adldap2/Adldap2-Laravel to auth against Active Directory.

Clearly I'm misunderstanding something hear. Why does AppController __construct() not dump the user?

</div>
  • 写回答

3条回答 默认 最新

  • dongshuo5101 2016-12-24 11:58
    关注

    This is because of changes in Laravel 5.3. If you need to use Auth in constructor you need to do it like so:

    public function __construct()
    {
         $this->middleware(function ($request, $next) {
                 if(\Auth::check() ) {
                    $this->user = \Auth::user();
                }
                var_dump($this->user);
    
                return $next($request);
            });
    }
    

    This change was described in upgrade guide to Laravel 5.3 - https://laravel.com/docs/5.3/upgrade#upgrade-5.3.0 look at section Session In The Constructor

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 用ucinet怎么计算子群体个数和核心边缘结构拟合度
  • ¥15 nrf52810-c三个a 程序
  • ¥15 lego-loam跑出来的roll误差很大
  • ¥50 求一个半透明没有锯齿的圆角窗体的实现例子
  • ¥15 STM32cubeMX里的FreeRTOS无法释放内存
  • ¥15 CATIA有些零件打开直接单机确定终止
  • ¥15 请问有会的吗,用MATLAB做
  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度