dongzha0813 2018-08-01 04:28
浏览 29
已采纳

如何从lalavel中的控制器中间件传递cookie作为参数?

I am a beginner in laravel. I am trying to pass a parameter from middleware from controller like this:

if(isset($_COOKIE['name']))
    {   
        return $next($request->attributes->add(['name' => strval($_COOKIE['name'])]));
    }

However, I got this error message:

"Type error: Argument 1 passed to Symfony\Component\HttpFoundation\Response::prepare() must be an instance of Symfony\Component\HttpFoundation\Request, null given"

I tried to convert the cookie value as string before passing it, but it did not work. How can I pass the pass the cookie as parameter? I do not want to get the value of cookie using $_COOKIE['name']. My laravel version is 5.5. Thank you!

  • 写回答

1条回答 默认 最新

  • dpt8910 2018-08-01 04:49
    关注

    Try merging the cookie value in with the request input:

    $merged = $request->merge(['name' => $request->cookie('name')]);
    
    return $next($merged);
    

    Keep in mind this will overwrite any input values named name so use a unique key.

    However, this isn't really necessary, as the request has access to the cookie throughout it's lifecycle:

    // MyController or MyModel or MyServiceProvider...
    if (request()->hasCookie('name')) {
        $cookie = request()->cookie('name');
        // do stuff with cookie
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog