dosrmo0442 2018-07-03 16:22
浏览 201
已采纳

在Laravel请求对象中使用变量名称

I need to be able to loop through a list of laravel request variables and do something with them. I want to be able to use a variable when calling the request object so that I can run it in a loop instead of writing a line of code for every one.

For example, my text inputs may have names that look something like this

contact_main_name
contact_main_telephone
contact_main_email

contact_sub_name
contact_sub_telephone
contact_sub_email

contact_backup_name
contact_backup_telephone
contact_backup_email

In my request, I don't want to have to write

$request->contact_main_name
$request->contact_main_telephone

For each different type of contact I may have, I want to be able to loop through them like so

$contactTypes = [
    'main',
    'sub',
    'backup',
    'head'
];

    foreach($contactTypes as $type){
        //Start a new contact
        $contact = new Contact;
        $contact->type = $type;
        $contact->name = $request->${"contact_".$type."_name"};
        $contact->telephone = $request->${"contact_".$type."_telephone"};
        $contact->email = $request->${"contact_".$type."_email"};
        $contact->save();
    }

How would i use a variable name when calling a laravel $request so that I can just build an array of possible types and loop through them all?

Note I know i can edit the input fields themselves to look something like name="contact[type][name]" and then loop through them, but I cant be changing the input names, I have to do it via php in the controller itself.

  • 写回答

2条回答 默认 最新

  • doutun1875 2018-07-03 16:28
    关注

    As answered in comments, to do this, change the method of calling the input and use the actual input() function itself.

    $contactTypes = [
        'main',
        'sub',
        'backup',
        'head'
    ];
    
    foreach($contactTypes as $type){
        //Start a new contact
        $contact = new Contact;
        $contact->type = $type;
        $contact->name = $request->input("contact_".$type."_name");
        $contact->telephone = $request->input("contact_".$type."_telephone");
        $contact->email = $request->input("contact_".$type."_email");
        $contact->save();
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集