Rubén Esteban
Rubén Esteban

Reputation: 31

Laravel 8 - Setting a cookie in response not working

I'm using Laravel 8 for my backend and I'm trying to store my auth token in a cookie. I want to set that cookie in my controller response, and I'm trying this way:

return response()->cookie('token', $tokenResult->accessToken, 10000);

The problem here is that Laravel can not find cookie method. According to Laravel 8 documentation, cookie() is a method from ResponseTrait, but Laravel is trying to get it from Macroable trait:

BadMethodCallException: Method Illuminate\Routing\ResponseFactory: :cookie does not exist. in file /var/www/html/t2t-api/vendor/laravel/framework/src/Illuminate/Macroable/Traits/Macroable.php

How could I solve this issue? Thank you.

P.S. It seems to work if I add a parameter to response() like this:

return response('Hello World')->cookie('token', $tokenResult->accessToken, 10000);

But I need a JSON response instead of this.

Upvotes: 2

Views: 1036

Answers (1)

AxissXs
AxissXs

Reputation: 731

You should use cookie on a new \Illuminate\Http\Response

$response = new \Illuminate\Http\Response();
return $response->cookie("name","value",360);

Upvotes: 2

Related Questions