如何从 laravel 中的控制器将 cookie 作为参数从中间件传递?
How to pass cookies as parameters from middleware from controller in laravel?
我是 laravel 的初学者。我正在尝试从控制器传递来自中间件的参数,如下所示:
if(isset($_COOKIE['name']))
{
return $next($request->attributes->add(['name' => strval($_COOKIE['name'])]));
}
但是,我收到此错误消息:
"Type error: Argument 1 passed to
Symfony\Component\HttpFoundation\Response::prepare() must be an
instance of Symfony\Component\HttpFoundation\Request, null given"
我试图在传递之前将 cookie 值转换为字符串,但没有成功。如何将 cookie 作为参数传递?我不想使用 $_COOKIE['name']
获取 cookie 的值。我的 laravel 版本是 5.5。谢谢!
尝试将 cookie 值与请求输入合并:
$merged = $request->merge(['name' => $request->cookie('name')]);
return $next($merged);
请记住,这将覆盖所有名为 name
的输入值,因此请使用唯一键。
然而,这并不是真正必要的,因为请求在其整个生命周期中都可以访问 cookie:
// MyController or MyModel or MyServiceProvider...
if (request()->hasCookie('name')) {
$cookie = request()->cookie('name');
// do stuff with cookie
}
我是 laravel 的初学者。我正在尝试从控制器传递来自中间件的参数,如下所示:
if(isset($_COOKIE['name']))
{
return $next($request->attributes->add(['name' => strval($_COOKIE['name'])]));
}
但是,我收到此错误消息:
"Type error: Argument 1 passed to Symfony\Component\HttpFoundation\Response::prepare() must be an instance of Symfony\Component\HttpFoundation\Request, null given"
我试图在传递之前将 cookie 值转换为字符串,但没有成功。如何将 cookie 作为参数传递?我不想使用 $_COOKIE['name']
获取 cookie 的值。我的 laravel 版本是 5.5。谢谢!
尝试将 cookie 值与请求输入合并:
$merged = $request->merge(['name' => $request->cookie('name')]);
return $next($merged);
请记住,这将覆盖所有名为 name
的输入值,因此请使用唯一键。
然而,这并不是真正必要的,因为请求在其整个生命周期中都可以访问 cookie:
// MyController or MyModel or MyServiceProvider...
if (request()->hasCookie('name')) {
$cookie = request()->cookie('name');
// do stuff with cookie
}