harunB10
harunB10

Reputation: 5197

Form checkbox field value is not getting passed to Laravel controller

In my registration form, I have a checkbox where a user can accept to receive newsletters.

In create function I want to display all passed data:

protected function create(array $data)
{
    dd($data);
}

The name of my checkbox field is newsletter. When I do dd(), I don't get the value for the newsletter, only for: name, email and password.

If I add this newsletter to Validator then it is shown.

protected function validator(array $data)
{
    return Validator::make($data, [
        'name'       => 'required|max:255',
        'email'      => 'required|email|max:255|unique:users',
        'password'   => 'required|min:6|confirmed',
        'newsletter' => 'required',
    ]);
}

Now, when I do dd() it is passed, but I don't want this checkbox to be required. It should be optional. Should I change something in Validator or?

Upvotes: 1

Views: 1849

Answers (2)

sepehr
sepehr

Reputation: 18445

Regardless of the backend, when a checkbox is not checked, its value won't be sent as part of the request to the server. That's how browsers work and that's why you won't be seeing a newsletter field when dumping the request.

However, when you use Laravel's validator and mention the field in the rules, Laravel does it for you and sets its value. To not to make it required, use the sometimes rule.

That would do it just for the purpose of dumping the data. But when implementing the real logic, instead of dumping data, you'll hopefully be utilizing the given request instance, facade or helper which will return a falsy value for non-existent parameters. So, you're just fine without adding the additional rule.

Or, you can set a default value for the newsletter field making sure if the data is not there, new registrations will happen with the desired default state.


By the way, you wanna make sure that your controller method is accepting a Request instance instead of an array.

Upvotes: 4

Jerodev
Jerodev

Reputation: 33186

Your newsletter field is a checkbox. When a html form is submitted and the checkbox is not checked, this field will not be available in the posted data. If the checkbox is checked it will be available. This is default html behavior, nothing you can do about this.

To check if the checkbox has been checked in your code, you can use the following:

$checked = array_key_exists('newsletter', $data);

Upvotes: 0

Related Questions