Auth :: user () returns null

I am using Laravel 5.2 and have a problem with middleware. There is code in route.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,
     ];

Adminminpan.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 returns null. Thanks for the suggestions!
+5
source share
2 answers

Any route that uses Auth() must be encapsulated in the web middleware. You are close, just move Route::group(['prefix' => 'admin'], ...) to the group above.

 Route::group(['middleware' => 'web'], function () { Route::auth(); Route::get('/', ' HomeController@index '); // Moving here will ensure that sessions, csrf, etc. is included in all these routes Route::group(['prefix'=>'admin', 'middleware' => 'admin'], function(){ Route::get('/', function(){ return view('admin.index'); }); Route::get('/user', function(){ return view('admin.user'); }); }); }); 
+12
source

I came across a situation where Auth::user() always returns null , because I tried to get User in the controller constructor.

I realized that you cannot access an authenticated user in your controller constructor because the middleware is not already running.

Alternatively, you can define Closure-based middleware directly in your controller constructor.

 namespace App\Http\Controllers; use App\User; use Illuminate\Support\Facades\Auth; use App\Http\Controllers\Controller; class ProjectController extends Controller { protected $user; /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware(function ($request, $next) { $this->user = Auth::user(); return $next($request); }); } } 
+5
source

Source: https://habr.com/ru/post/1242118/


All Articles