I'm building a laravel-app where I'm connecting mailchimp to the contact-form. The user has to accept conditions and has the possibility to receive the newsletter by checking a checkbox. Right now, when the user accepts both the conditions and the newsletter, the form is submitted successfully, but when the user does not check the newsletter checkbox, the form is not submitted and I don't really know why.
here the input
<input name="conditions" value="1" type="checkbox" class="custom-control-input" id="applyConditions" required>
<input type="checkbox" name="newsletter" class="custom-control-input" id="contactNewsletterSubscribe">
and my controller:
class ContactController extends Controller
{
public function store()
{
$validator = Validator::make(request()->all(), [
'email' => ['required', 'email'],
'name' => ['required', 'string'],
'phone' => ['string'],
'subject' => ['required', 'string'],
'message' => ['required', 'string'],
'conditions' => ['accepted', 'boolean'],
]);
if ($validator->fails()) {
return response()
->json($validator->messages(), 400);
}
if (request()->has('newsletter')) {
Newsletter::subscribePending(request()->email);
if (!Newsletter::lastActionSucceeded()) {
return response()
->json($validator->messages(), 400);
}
}
Mail::to('[email protected]')
->send(new ContactUsMessage([
'email' => request()->email,
'name' => request()->name,
'phone' => request()->phone,
'subject' => request()->subject,
'message' => request()->message,
]));
return response()->json('OK', 200);
}
}
When I check both conditions and the newsletter checkboxes, the form data returns:
conditions: 1
newsletter: on
When conditions are accepted but the newsletter checkbox is unchecked, the form data returns:
conditions: 1
newsletter: undefined
Can someone tell me what I'm doing wrong?
EDIT
I'm sending the form data with jquery/axios:
if ($('#contact input[name="newsletter"]:checked')) {
formData.append(
"newsletter",
$('#contact input[name="newsletter"]:checked').val()
);
} else {
formData.append(
"newsletter",
$('#contact input[name="newsletter"]').val()
);
}
val()every time?