50

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!
user2094178
  • 9,204
  • 10
  • 41
  • 70
imladris
  • 565
  • 2
  • 5
  • 9

9 Answers9

81

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);
        });
    }
}
Hemerson Varela
  • 24,034
  • 16
  • 68
  • 69
56

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');
        });
    });
});
camelCase
  • 5,460
  • 3
  • 34
  • 37
  • In my case I created a custom route file as routes/admin.php and hooked it inside boot() method of RouteServiceProvider.php. Since I wanted to have Auth::user() working inside my middleware I needed to pass ``web`` as `first` element of array which I passed to middleware chaining. i.e `Route::prefix('admin')->middleware(['web', 'admin'])->namespace($this->namespace)>group(base_path('routes/admin.php'));`. Passing it first element is important as it wont work as second. – Arvind K. Jul 12 '21 at 14:47
2

Define middleware in the constructer of your controller and it will do the trick here

public function __construct()
{
    $this->middleware('auth:api');
}
kp85
  • 371
  • 3
  • 9
1

I had the same problem because i did not set the table name.

/**
 * The table associated with the model.
 *
 * @var string
 */
protected $table = 'users';
  • thank you so much, I spent quite some time to fix this issue. In the past I added table attribute to each model – Angel M. May 20 '20 at 05:39
1

I found a solution in an old code

    function getAuth($guard, $get)
{
    return auth($guard)->user()->$get;
}

add this ^ as a helper function and use it wherever you want ex:

getAuth('user', 'id');
0

You can use it like this.

$this->middleware(function ($request, $next) {
            //Your Code Here 
            return $next($request);
        });

It has worked for me.

-1

just include your authentication middleware in call

$user = auth('middleware')->user()
MilBan
  • 1
-2
Route::middleware('auth:api')->group(function () {
    Route::get('/details', 'UserController@details');
});
David Buck
  • 3,752
  • 35
  • 31
  • 35
sam
  • 1
-6

My Auth::user() return null in view when

  • I don't have users table in database
  • I don't have id field as primary key of table users
Linh
  • 57,942
  • 23
  • 262
  • 279