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条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?