Set a Laravel 7 Cookie From API Request

Viewed 1807

i'm having problem setting a cookie or a session through API request , I tried to use the web middleware & tried to move the route to the web folder , nothing really works. My Route: web.php

Route::get('api/add-item-to-cart' ,'CartController@addItem')->name('cart.add');

My Controller: CartController@addItem

setcookie('name','value');
$CartData['user_id'] = Cookie::get('guest_id');
//Always Returns Null

Die and Dump the Cookie::get() returns :

array:7 [▼
  "fdsfsda" => null
  "name" => "value"
  "token" => null
  "guest_id" => null
  "XSRF-TOKEN" => "JwqisWA0rMCLnFmBitqK8Va0lXwCMjP7A2Ks2Bi1"
  "uk_fashion_shop_session" => "ngMrvLmPQZ8SrfnonA9pVLFID05OIk1Su0hOIUrZ"
  "io" => null
]

So the cookie is actually getting set , but without a value Notes: The Cookie is getting set , but there is no value assigned to it for some reason but when i use the laravel way , the cookie is not even set
//The Cookie::queue(Cookie::make('guest_id', md5(rand(1,500)))); is not setting anything at all
my session file is as the default

1 Answers

I'm not sure why your cookie is not set. But to be sure that it's strictly laravel issue, maybe missing dependency, specify appriopriate details about your cookie, using for example response API.

return response('Hello World')->cookie(
    'name', 'value', $minutes, $path, $domain, $secure, $httpOnly
);

Be sure, you set expiration date which is greater than current timestamp (it will expire almost instantly otherwise), set domain exactly as your domain (DNS specified) and path, for example global / for testing purpouse.

UPDATE You can also debug cookies in your browser.

In Mozilla CTRL+SHIFT+I --> Data --> Cookies.

And after that, you can see all cookies which are stored by your browser.

Related