Laravel 5 checkbox processing

One of the annoyances of HTML form processing is that checkboxes are not returned if they are unchecked.

This causes an issue if you just want to use Laravel’s automatic validation of forms and then want to be able to pass the validated form response to the model. Whilst it is possible to manage checkboxes in the controller it always strikes me as messy. My solution is below. There will always be detractors that claim the validator is not the place for this, my argument is that I am validating that what comes from the validator is either true or false and not true or missing.

Since the rules area of the request object is actually a method, it is possible to interact with the content of the request.

So, in my EditUserRequest class, where I have a checkbox named ‘is_admin’;

	public function rules()
		// default the value of the is_admin checkbox
		$this->merge(['is_admin' => $this->input('is_admin', 0)]);

		return [
			'name' => 'required|min:5',
			'email' => 'required|email',

I merge back into the request, the value of the input, or a default (the second option to Request->input) of 0. This sets the checkbox element to 0 if it is not present.

Then in the controller, I can use the simple;


Leave a comment

Your email address will not be published. Required fields are marked *

10 thoughts on “Laravel 5 checkbox processing