0

Whenever I set a cookie from Laravel like this :

return redirect($this->redirectTo)->withCookie(cookie('token', auth()->user()->api_token, 60)); // set cookie for 60 minutes

And I want to get that cookie from Javascript like this:

var token = localStorage.getItem('token');
console.log(token);

But it always return null

I'm pretty sure cookie is already set on browser and not null using cookie manager add-ones.

Any ideas?

Hamed Kamrava
  • 12,359
  • 34
  • 87
  • 125
  • I think you are confused between cookie and localStorage. Access the cookie using `console.log(document.cookie);` https://stackoverflow.com/questions/19867599/what-is-the-difference-between-localstorage-sessionstorage-session-and-cookies – linktoahref Jul 24 '17 at 05:55

2 Answers2

1

Are you sure that Laravel cookies stored in localStorage ?

To get cookies using JavaScript you can use document.cookie.


To get a cookie by name you can use this code:

function getCookie(name) {
  var value = "; " + document.cookie;
  var parts = value.split("; " + name + "=");
  if (parts.length == 2) return parts.pop().split(";").shift();
}

var token = getCookie('token');

console.log(token);

Code copied from here

Mohamed Abbas
  • 2,228
  • 1
  • 11
  • 19
0

Cookie::queue($name, $value, $minutes); This will queue the cookie to use it later and later it will be added with the response when response is ready to be sent. You may check the documentation on Laravel website. Update (Retrieving A Cookie Value):$value = Cookie::get('name');