mardi 3 juillet 2018

Using variable name in Laravel request object

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.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire