paaaaayns's avatar

Laravel with SweetAlert2: Form Submission Issues

Hi everyone,

I’m working on a Laravel project and using SweetAlert2 to display a success alert when a form is submitted successfully. Here’s my current setup:

Form Layout:

<form method="POST" action="{{ route('reg.store') }}" id="RegistrationForm">
    @csrf
    <x-forms.field-container class="sm:col-span-4">
        <x-forms.label for="first_name">
            First Name <span class="text-red-500">*</span>
        </x-forms.label>
        <x-forms.input
            type="text"
            id="first_name"
            name="first_name"
            :value="old('first_name')"
            autocomplete="off" />
        <x-forms.error name="first_name" />
    </x-forms.field-container>
</form>

Store Method in Controller:

public function store(Request $request)
{
    $validatedData = $request->validate([
        'first_name' => ['required', 'string', 'max:255'],
        'middle_name' => ['nullable', 'string', 'max:255'],
        'last_name' => ['required', 'string', 'max:255'],
    ]);

    return response()->json([
        'success' => true,
        'message' => 'Registration successful.',
    ], 201);
}

SweetAlert2 Script:

The Problem

  1. If I include e.preventDefault(); in my script, it prevents Laravel from displaying the validation errors in the <x-forms.error> component.
  2. If I remove e.preventDefault();, the form submits properly, and Laravel displays the errors, but when the form is successful, it only returns the JSON response, and SweetAlert2 doesn't trigger.

What I Want to Achieve

  • Display the validation errors in the <x-forms.error> component when the form fails validation.
  • Show a SweetAlert2 success message when the form submission is successful.

Has anyone encountered this issue before or knows how to resolve it? How can I display both Laravel validation errors and the SweetAlert2 success message effectively?

Thanks in advance!

0 likes
0 replies

Please or to participate in this conversation.