Session not saved after Auth::attempt

33 Views Asked by At

I try to update my application from Laravwl 10 to Laravel 11. For the front end I use React + Inertia.

public function login(Request $request): JsonResponse
{
    $request->validate([
        'username' => 'required',
        'password' => 'required',
    ]);

    if (!Auth::attempt([
        'username' => $request->username,
        'password' => $request->password,
    ], true)) return response()->json([
        'message' => 'The provided credentials do not match our records.',
    ], 422);

    return response()->json([
        'message'   => 'Successfully login',
        'data'      => Auth::user(),
    ]);
}

This works just fine in Laravel 10. Auth::user() exists (success login), but the session not save my auth. For the session driver I use database and after I check my database, the user_id is null.

1

There are 1 best solutions below

1
AntonyMN On

From the official documentation, when you perform Auth::attempt($credentials) you should regenerate the user's session to prevent session fixation using the command $request->session()->regenerate().

public function login(Request $request): JsonResponse
{
    $request->validate([
        'username' => 'required',
        'password' => 'required',
    ]);

    $credentials = [
        'username' => $request->username,
        'password' => $request->password,
    ];

    if (Auth::attempt($credentials)) {
        $request->session()->regenerate();

        return response()->json([
            'message'   => 'Successfully login',
            'data'      => Auth::user(),
        ]);
    } else {
       return response()->json([
        'message' => 'The provided credentials do not match our records.',
       ], 422);
    }
}