Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auth::user() returns null

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!
like image 219
imladris Avatar asked Feb 02 '16 17:02

imladris


People also ask

Why Auth:: user returns null?

So the answer to this issue is that if you have multiple authentication routes as well as multiple authentication mechanisms (i.e. guards), you have to tell Laravel's middleware which monitor those various routes, which guard to use per route group. class Authenticate { /** * Handle an incoming request.

What does Auth :: check () do?

In other words, Auth::check() calls Auth::user() , gets the result from it, and then checks to see if the user exists. The main difference is that it checks if the user is null for you so that you get a boolean value. As you can see, it calls the user() method, checks if it's null, and then returns a boolean value.

What is auth middleware laravel?

Using the Auth Middleware Middlewares provide a convenient mechanism for filtering HTTP requests entering your application. For example, Laravel includes a middleware that verifies the user of your application is authenticated. If the user is not authenticated, the middleware will redirect the user to the login screen.

How to check if currentuser State IS NULL or not?

The currentUser API only exposes two types of values: null or non-null, so you can’t tell the difference between states 1 and 2. A null value could mean either one, and we have no way to immediately verify this!

When should I set up a user Auth observer?

I’ll annotate that more clearly with some log messages: Note that the user auth state is unknown only before the callback is invoked the first time, so you should set up your UI to show that splash screen or loading indicator before setting up this observer. And you should set it up as soon as possible after your app launches.

How do I get current user object in Firebase Auth SDK?

In fact, the Firebase Auth SDK requires at least one, and possibly two steps, to take in order to deliver a valid current user object: Check and load the persisted user ID token from disk. Refresh the user’s ID token if needed (hourly).


2 Answers

I faced a situation where Auth::user() always returns null, it was because I was trying to get the User 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.

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);         });     } } 
like image 124
Hemerson Varela Avatar answered Sep 25 '22 14:09

Hemerson Varela


Any route that uses Auth() must be encapsulated in the web middleware. You're close, just move your Route::group(['prefix' => 'admin'], ...) into 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');         });     }); }); 
like image 30
camelCase Avatar answered Sep 24 '22 14:09

camelCase