mercredi 24 avril 2019

How to submit unchecked checkboxes to controller

Ok first I have a "settings" table on my database in which I have the fields "name" and "value" its a configuration kind of table where the value could be anything from string to boolean values etc.

Now on my blade, I have a form with various inputs "texts" "selects" "checkboxes" etc. When submitting the form on the controller I run a foreach where for each attribute of the $request i store its key as the name and its value as its value on the database.

    $agency_id = Auth::user()->agency->id;
    $settings = AgencySettings::whereAgencyId($agency_id)->get();
    foreach ($request->except('_token') as $key => $value)
    {
        $setting = $settings->where('name','=',$key)->first();
        if (boolval($setting))
        {
            $setting->value = $value;
            $setting->update();
        }else{
            $setting = new AgencySettings;
            $setting->agency_id = $agency_id;
            $setting->name = $key;
            $setting->value = $value;
            $setting->save();
        }
    }

All works well except the unchecked checkboxes which are not inside the $request. I know I can handle them like so $request->has('name_of_checkbox') but because of the dynamic nature of the table on the database, I don't want to have hardcoded on my Controller the name of a specific setting.

My goal is that the code on my Controller will be the same regardless the number of different settings I will use on my frontend (maybe in the future there will be a need to add more).

So my question, is there a way to handle those checkboxes serverside without having to refer to them specifically, or a way to always return the value of the checkboxes to the server despite its state?

My first thought is to go with javascript and hidden inputs, but maybe there is a better way.




Aucun commentaire:

Enregistrer un commentaire