Home > database >  how to fix Cookies not setting in laravel 9?
how to fix Cookies not setting in laravel 9?

Time:04-28

I'm trying to set a httpOnly cookie for token but it's not saving cookie.

I'm trying to login users via OTP and when user entered correct OTP, I'll sign them in app and so far I've done it like below :

$user = User::where('mobile_number', $request->mobileNumber)->first();

if ($user) {
    Auth::login($user);

    $token = $user->createToken('authToken')->accessToken;

    $cookie = cookie('token', $token, 60 * 24 * 24); // 24 day

    return response([
        'status' => 'success',
        'message' => 'loggedIn',
        'user' => auth()->user(),
    ])->withCookie($cookie);

}else{
    return response()->json([
        'status' => 'success',
        'message' => 'notExist'
    ], 200);
}

User will successfully login and if I refresh the page I should login again, and when I check Application\Storage\Cookies in Firefox and Storage\Cookies in chrome there's no sign of returned cookie(even if I don't refresh the page cookies won't be saved at all).

I'm using Laravel Passport, and so far, i don't think there should be any problem related to VUE side, since cookies not even saving in browser.

I've also tried to add more cookies to just test if everything work, but same problem happened again and nothing saved in browser.

I've also tried other solutions in Stackoverflow but they didn't worked.

enter image description here

Edit 01 : Removed refresh page... Edit 02 : Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse and Queue tested.

CodePudding user response:

Use the Cookie Facade that Laravel provides:

use Illuminate\Support\Facades\Cookie;
 
Cookie::queue('token', $token, 60 * 24 * 24);

In your Kernel.php, search for AddQueuedCookiesToResponse and uncomment it if it's commented.

CodePudding user response:

Well, i found it, looks like problem was from VUE side actually. app URL was 127.0.0.1 for default in env file, but in VUE it was calling API via Localhost, and it was working but cookie wasn't saving due to this conflict, and when i changed it to 127.0.0.1 as default baseURL in axios, it worked.

  • Related