dongzha0813 2018-08-01 04:28 采纳率: 0%
浏览 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 代写uni代码,app唤醒
  • ¥15 全志t113i启动qt应用程序提示internal error
  • ¥15 ensp可以看看嘛.
  • ¥80 51单片机C语言代码解决单片机为AT89C52是清翔单片机
  • ¥60 优博讯DT50高通安卓11系统刷完机自动进去fastboot模式
  • ¥15 minist数字识别
  • ¥15 在安装gym库的pygame时遇到问题,不知道如何解决
  • ¥20 uniapp中的webview 使用的是本地的vue页面,在模拟器上显示无法打开
  • ¥15 网上下载的3DMAX模型,不显示贴图怎么办
  • ¥15 关于#stm32#的问题:寻找一块开发版,作为智能化割草机的控制模块和树莓派主板相连,要求:最低可控制 3 个电机(两个驱动电机,1 个割草电机),其次可以与树莓派主板相连电机照片如下: