Home » Php » php – Laravel set cookie in API not set

php – Laravel set cookie in API not set

Posted by: admin February 25, 2020 Leave a comment

Questions:

I using laravel 5 as Rest API, and I want to set a cookie in controller:

return response()->json(['success' => $data], $this-> successStatus)->cookie('name', 'myvalue');

this return with response cookie successfully, but can not access in front, I also used:

Cookie::queue($name, $value);

Or

Cookie::queue(Cookie::make('cookieName', 'value'));

Or all way in google, stackoverflow, but none of these set cookie in browser, I need to set http only cookie in browser via laravel controller. how can i do this?

I also used php cookie, no success

How to&Answers:

Cookies will be set on web middleware group only not api. According to docs, Laravel comes with web and api middleware groups that contain common middleware you may want to apply to your web UI and API routes:

/**
 * The application's route middleware groups.
 *
 * @var array
 */
protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        //...
    ],

    'api' => [
        'throttle:60,1',
        'auth:api',
    ],
];

As you can see, EncryptCookies and AddQueuedCookiesToResponse middlewares are applied to web group only but not api.

// This works and sets encrypted cookie on response.
Route::group(['middleware' => ['web']], function () {
    return response()
        ->cookie('name', 'value');
});

// This won't set cookie on response.
Route::group(['middleware' => ['api']], function () {
    return response()
        ->cookie('name', 'value');
});

Answer:

You may use

$response = new \Illuminate\Http\JsonResponse(['success' => $data], $this->successStatus);
$response->withCookie(cookie($cookieName, $cookieVal, 45000));
return $response;

Illuminate\Http\JsonResponse