Ad

Trying To Get Value Of Checkbox From Form To Controller

- 1 answer

I'm trying to do something that allows me to upload photos when I check a checkbox control. I got the client side working correctly such that when the checkbox is checked the upload controls are displayed and the form validates correctly.

However, in my controller I need to take some action if my checkbox was checked (true) calling a certain method. If it isn't checked (false) I perform some other action.

In my html page I have the following:

<form action="/supplier/submit/plan" method="post" role="form" id="plan-form">
...   
   <input name="checkingPhotos" type="checkbox" id="chkPhotos" />
   <label for="chkPhotos">I want to include photos in this plan.</label>
...
</form>

However, in my controller I just want to for now see if I get the correct value in my checkbox. For this I did something simple as:

 public function submitPlan(Request $request)
    {
        $checkboxValue = $request->input('checkingPhotos');
        dd($checkboxValue);
    }

The result is null is printed whether I check the checkbox or not. My route also looks like this:

Route::post('/submit/plan', '[email protected]');

Can someone please tell me what I am doing wrong here? I just want to see the value 1 / True or 0 / False in my controller method.

Ad

Answer

Value

The real issue is that you don't have a value for your check box. Add a value, and your problem is solved. It should be:

<input name="checkingPhotos" type="checkbox" id="chkPhotos" value="1" />

[] creates an array

The answer Dylan Kas submitted about changeing the name to add [] works, but not for the reasons you think. Lets take a look:

<input name="checkingPhotos[]" type="checkbox" id="chkPhotos" />

Will pass in the post string:

 checkingPhotos[]=On

Which, in PHP will automatically be turned into an array.

Refernce Frame Challenege

Why do you have a checkbox in the first place? Is the checkbox needed? Why not just check for the existence of the file.

$validated = $request->validate([
    //... other fields here.
    'image' => 'mime:png,gif,jpeg|max:10000' //set max to file size limit you want
]);
$plan = new SupplierPlan($validated);
if($request->has('image')){
   $plan->image = $request->image->store();
}
$plan->save();
// ... flash message, return view or redirect
Ad
source: stackoverflow.com
Ad