duandie5707 2018-04-27 06:59
浏览 612
已采纳

如何将数组中的值从控制器传递到视图

I m new to Laravel and I am trying to pass values from a controller which I have received from a <form> to a view and display the same in text boxes. Although, I have figured out how to do the same using method chaining but I would like to pass the values using an array and show the same into the textboxes in the view.

What I expect to do?

In the controller, instead of method chaining:

return view('showvalues')->with(['name'=>$name, 'address'=>$address]);

Code so far,

controller

 public function showvalues(Request $request)
    {
        $name=$request->get('name');
        $address=$request->get('address');
        $pass=$request->get('password');
        $arr=array("$name","$address","$pass");

        return view('showvalues')->with('name',$name)->with('address',$address);
    }

Show values in showvalues view:

<html>
    <head>

    </head>
    <body>
        <h1>
            Show Value Page.
        </h1>
        <input type="text" name="n1" value="<?php echo $name;?>" /><br>
        <input type="text" name="n3" value="<?php echo $address;?>" />
    </body>
</html>
  • 写回答

4条回答 默认 最新

  • douchilian1009 2018-04-27 07:01
    关注

    Use the compact method as the second argument to view:

    public function showvalues(Request $request)
    {
        $name = $request->get('name');
        $address = $request->get('address');
        $pass = $request->get('password');
    
        return view('showvalues', compact('name', 'address', 'pass'));
    }
    

    The variables will be available in your view file by the same name, you can display them like:

    {{ $name }}
    {{ $address }}
    {{ $pass }}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
  • dongmo6937 2018-04-27 07:01
    关注

    Pass array as second argument to view():

    return view('showvalues', ['name'=>$name, 'address'=>$address]);
    

    Btw, did you try to open Laravel's manual?

    评论
  • dongtou8736 2018-04-27 07:07
    关注

    You need to return all form inputs with compact function.

    Controller

    public function showvalues(Request $request)
    {
        $form = $request->all();
    
        return view('showvalues', compact('form'));
    }
    

    View

    {{ $form['name'] }}
    {{ $form['address'] }}
    
    评论
  • duanchi4184 2018-04-27 07:09
    关注

    what about

    return view('showvalues')->withName($name);
    

    Or

    return view('showvalues')->with(['name'=>$name]);
    
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 Java环境配了,但启用不成功。
  • ¥15 求一个智能家居控制的代码
  • ¥15 ad软件 pcb布线pcb规则约束编辑器where the object matpcb布线pcb规则约束编辑器where the object matchs怎么没有+15v只有no net
  • ¥15 虚拟机vmnet8 nat模式可以ping通主机,主机也能ping通虚拟机,但是vmnet8一直未识别怎么解决,其次诊断结果就是默认网关不可用
  • ¥20 求各位能用我能理解的话回答超级简单的一些问题
  • ¥15 yolov5双目识别输出坐标代码报错
  • ¥15 这个代码有什么语法错误
  • ¥15 给予STM32按键中断与串口通信
  • ¥15 使用QT实现can通信
  • ¥15 关于sp验证的一些东西,求告知如何解决,