laravel 5.4 : cant access Auth::user() in the __construct method

元气小坏坏 提交于 2019-12-01 15:07:43

问题


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

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

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


回答1:


As the doc says :

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.

So try this :

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

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



回答2:


You Have To define Auth method before you load your class as you use your namespace.See the example below:

namespace App\Http\Controllers\Admin;

use Illuminate\Support\Facades\Input;
use Auth;

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

And After you can clean your cache if required. php artisan config:cache



来源:https://stackoverflow.com/questions/45055618/laravel-5-4-cant-access-authuser-in-the-construct-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!