Search code examples
laravelcookies

how to fix Cookies not setting in laravel 9?


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.


Solution

  • I found it. It looks like the problem was from Vue side actually. App URL was 127.0.0.1 for default in env file, but in Vue it was calling the API via Localhost, and it was working, but the cookie wasn't saved due to this conflict. When I changed it to 127.0.0.1 as default baseURL in Axios, it worked.