How to set cookie in custom command and get it in middleware Laravel

Viewed 548

I am looking for way to set cookie in console custom command and get it in middleware in Laravel(version - 5.2). This is what I am trying

In custom command,

Cookie::queue('login', 'true', 1);
$cookies = array('login' => true);

In middleware,

Cookie::get('login') // unable to get here set cookie

Calling route internally through custom command

$req = Request::create('/my/url', 'POST', $params, $cookies);
$res = app()->handle($req);
$responseBody = $res->getContent();

Reference symfony/http-foundation calling-routes-internally

Your assistance would be highly appreciated.

1 Answers

I would think that you have already created a middleware, suppose CookieMiddlware. So inside CookieMiddlware there is a handle method. There try to dd($request);.

For example:

public function handle($request, Closure $next)
{
    dd($request);
    //return $next($request);
}

Register your middleware and then apply it on a route. Hit that route and you will see full request data. There you will find cookies. Open it and play with it.

If you have set the cookies properly you can get it from request in middleware.

+cookies: ParameterBag {#45 ▼
#parameters: array:3 [▼
  "laravel_session" => "FDyl3cnxEy3VDIiivxLQmDDbyZuJggeU8"
  "XSRF-TOKEN" => "7TQrk9QZKrpPPrgoaAXNOIZlThrePlesjQJ"
  "etc" => "2zbP5hem9RcvBcQwBz8UewwZxWQxQAcA4"
 ]
}

And you can access it like $request->cookie('name'); something like that, I think you know the rest. It may help you.

Checked in this way.

$cookies = array('login' => "akhtar");
$ar = json_encode($cookies);
Cookie::queue('test',$ar,100);
dd(json_decode(Cookie::get('test')));
Related