Goodvin
1434
5
Laravel

Why Auth::user() return null from controller method ?

Posted 1 year ago by Goodvin

Hi! I'am develop an admin panel. And of course, it's guard by authentification. I want to retrieve user data after login. But controller method return null on Auth::user(). Why can it happened ?

As I understand, most commonly mistakes are retrieving user from controller and absence of web middleware. And I'am consider it.

Controller

namespace MyNamespace\App\Controllers\System;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

use App\Http\Controllers\Controller;

class UserController extends Controller
{
    public function index (Request $request) {

        $user = Auth::user();

        return response()->json($user, 200);
    }
}

Routes web.php

Route::group(['middleware' => ['web']], function () {

    Route::get('login', 'MyNamespace\App\Controllers\Auth\[email protected]')->name('login');

    Route::prefix('api')->group(function () {

        Route::prefix('system')->group(function () {

            Route::get('user', 'MyNamespace\App\Controllers\System\[email protected]');
        });

        Route::post('login', 'MyNamespace\App\Controllers\Auth\[email protected]');
        ...
    });
});

config/auth.php

    ...
    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => MyNamespace\App\Models\User\User::class,
        ],
    ],

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.