I use Laravel 5.2 and have a problem with middleware. There is the code in the routes.php
use Illuminate\Contracts\Auth\Access\Gate; Route::group(['middleware' => 'web'], function () { Route::auth(); Route::get('/', 'HomeController@index'); }); Route::group(['prefix'=>'admin', 'middleware' => 'admin'], function(){ Route::get('/', function(){ return view('admin.index'); }); Route::get('/user', function(){ return view('admin.user'); }); });
Kernel.php:
protected $routeMiddleware = [ ... 'admin' => \App\Http\Middleware\AdminPanel::class, ];
AdminPanel.php
namespace App\Http\Middleware; use Closure; use Illuminate\Support\Facades\Auth; use App\Role; class AdminPanel { public function handle($request, Closure $next) { $user = Auth::user(); dd($user); if($user){ $role = Role::whereName('admin')->first(); if($user->hasRole($role)){ return $next($request); } } return redirect('/'); }
So,
$user = Auth::user
()
always return null.
Thanks for suggestions!
Any route that uses
Auth()
must be encapsulated in theweb
middleware. You're close, just move yourRoute::group(['prefix' => 'admin'], ...)
into the group above.I faced a situation where
Auth::user()
always returnsnull
, it was because I was trying to get theUser
in a controller's constructor.I realized that you can't access the authenticated user in your controller's constructor because the middleware has not run yet.
As an alternative, you can define a Closure based middleware directly in your controller's constructor.