[Vuejs]-Laravel Inertia error alert is showing even if the form is not submitted

0👍

In your Vue code, you can add a success variable to track if the form submission was successful.

<script setup>
const form = reactive({
    prefix: null,
    name: null,
    contact_number: null,
    email_id: null
});

let success = false;

const submit = () => {
    axios.post('/create', form)
        .then(response => {
            // Set success to true and clear the form fields
            success = true;
            form.prefix = null;
            form.name = null;
            form.contact_number = null;
            form.email_id = null;
        })
        .catch(error => {
            // Handle errors here
            console.log(error.response.data);
        });
};
</script>

<div v-if="$page.errors">
    <div class="bg-orange-100 border-l-4 border-orange-500 text-orange-700 p-4" role="alert">
        <p v-for="error in $page.errors">{{ error }}</p>
    </div>
</div>

<div v-if="success">
    <div class="bg-green-100 border-l-4 border-green-500 text-green-700 p-4" role="alert">
        <p>Form submitted successfully!</p>
    </div>
</div>

Laravel side, you can use the with() method to pass a flash msg

$patient = Patient::create($request->validate([
    'prefix'            => 'required',
    'name'              =>'required|max:50|alpha:ascii',
    'contact_number'    =>'required',
    'email_id'          =>'required|email',
]));

return redirect()->route('patients.index')->with('success', 'Form submitted successfully!');

Then show it in view

@if(session('success'))
    <div class="bg-green-100 border-l-4 border-green-500 text-green-700 p-4" role="alert">
        <p>{{ session('success') }}</p>
    </div>
@endif

Leave a comment