Can't call Auth::user() on controller's constructor

淺唱寂寞╮ 提交于 2019-11-26 08:27:59

问题


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

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.

Any Ideas why?


回答1:


See 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.

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

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

    //
}



回答2:


Because you're attempting to access the instance before the middleware even fires. You can use request()->user() instead.




回答3:


class StudentController extends Controller
{

    public $role;

    public function __construct()
    {
        $this->middleware(function ($request, $next) {  
        if (!Auth::user()->hasPermission('usergroups')) {
            abort(404);
        }
            return $next($request);
        });
    }
}

Hope help you!!!

Update: Get your code inside

$this->middleware(function ($request, $next) {
//your code
return $next($request);
});


来源:https://stackoverflow.com/questions/39175252/cant-call-authuser-on-controllers-constructor

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