imladris
imladris

Reputation: 595

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!

Upvotes: 53

Views: 87611

Answers (9)

Dipesh Khanal
Dipesh Khanal

Reputation: 11

You can use it like this.

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

It has worked for me.

Upvotes: 0

Abderrahman Fodili
Abderrahman Fodili

Reputation: 143

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

Upvotes: 1

MilBan
MilBan

Reputation: 1

just include your authentication middleware in call

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

Upvotes: -1

kp85
kp85

Reputation: 441

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

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

Upvotes: 3

sam
sam

Reputation: 1

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

Upvotes: -2

Linh
Linh

Reputation: 60923

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

Upvotes: -6

Arvid de Jong
Arvid de Jong

Reputation: 31

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

/**
 * The table associated with the model.
 *
 * @var string
 */
protected $table = 'users';

Upvotes: 1

Hemerson Varela
Hemerson Varela

Reputation: 25792

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

Upvotes: 85

camelCase
camelCase

Reputation: 5598

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

Upvotes: 59

Related Questions