53

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!

0

9 Answers 9

84

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);
        });
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

This solves my problem, and I put all the process inside the middleware callback;
60

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');
        });
    });
});

1 Comment

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.
3

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

public function __construct()
{
    $this->middleware('auth:api');
}

Comments

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';

1 Comment

thank you so much, I spent quite some time to fix this issue. In the past I added table attribute to each model
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');

Comments

0

You can use it like this.

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

It has worked for me.

Comments

-1

just include your authentication middleware in call

$user = auth('middleware')->user()

Comments

-2
Route::middleware('auth:api')->group(function () {
    Route::get('/details', 'UserController@details');
});

1 Comment

middleware('auth:api') supports to only api requests
-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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.