Laravel: Passing a value of 0 back to controller from frontend

Viewed 308

I have a boolean field that is represented by 0 and 1 in my database.

if ($request->input('submitted')) {
       // do code
 }

This has been working because it's only been setting the field to 1 (true) but now there's a new flow that can revert the submission.
It has not been setting it back to 0 when I pass the value 0 in from the frontend and I assume it's because that condition is getting skipped since 0 would eval to null.

Is the best way to handle it:

if (isset($request->input('submitted'))) {
           // do code
}

or would strictly checking against null work better:

if ($request->input('submitted') !== null) {
     // do code
}
1 Answers

The simply approach parse your input to a boolean.

if ((bool) $request->input('submitted')) {

This will create the following results. Therefor removing your edge case.

(bool) "1" // true
(bool) "1" // false

An alternative approach is to use inbuilt PHP filter, it will parse a lot of cases more notably "true" and "false" to true and false.

if (filter_var($request->input('submitted'), FILTER_VALIDATE_BOOLEAN)) {
Related