Cannot call Auth :: user () in controller constructor

I am trying to check if a user has permission for a specific model. So far (with Laravel 5.2) I have added this code to the constructor:

public function __construct() { if (!Auth::user()->hasPermission('usergroups')) { abort(404); } } 

Now, after upgrading to Laravel 5.3, Auth::user() returns null when called from the controller constructor. If I call it in any other class method, it returns the current user.

Any ideas why?

+6
source share
2 answers

Look here :

Designer Session

In previous versions of Laravel, you could access session variables or an authenticated user in the controller constructor. It was never intended for an explicit feature of the structure. In Laravel 5.3, you cannot access a session or authenticated user in your controller constructor, since the middleware is not already running.

Alternatively, you can define Closure-based middleware directly in the controller constructor. Before using this function, make sure that your application works with Laravel 5.3.4 or higher:

 <?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 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 can also access the request session data or an authenticated user by type - the Illuminate \ Http \ Request class hints at the action of your controller:

 /** * 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'); // } 
+16
source

Because you are trying to access the instance before the middleware even fires. Instead, you can use request()->user() .

0
source

All Articles