Debug School

rakesh kumar
rakesh kumar

Posted on • Updated on

Explain the difference between wire:submit.prevent vs wire.submit in laravel livewire

Explain difference between wire:submit.prevent vs wire.submit ?

How you can prevent reloading page or navigating new url after form submission to database ?

How to set success message in component class controller function using public varaible $successMessage

How wire:model="message" is performing two-way-binding

How to redirect new url after form submission

How to redirect new page while we use wire:submit.prevent

what is the use of redirectAfterSubmit and dispatchBrowserEvent

wire:submit.prevent

<form wire:submit.prevent="handleSubmit">
Enter fullscreen mode Exit fullscreen mode

This directive prevent attached to wire:submit prevents the default form submission behavior. In this case, when the form is submitted, it triggers the handleSubmit method in the Livewire component without reloading the page or navigating away.
After handling the form submission in the handleSubmit method, you can choose to perform actions such as showing a success message or redirecting to a new page without the page reloading by using Laravel's redirection functions.
wire:submit:

<form wire:submit="handleSubmit">
Enter fullscreen mode Exit fullscreen mode

This directive doesn't include .prevent, so it doesn't prevent the default form submission behavior. When the form is submitted, it still triggers the handleSubmit method in the Livewire component, but after that, the default form submission behavior occurs.
After handling the form submission in the handleSubmit method, the browser performs its default action of either reloading the page or navigating to a new URL if you don't intervene with a redirection.
Comparison:

With wire:submit.prevent, you have full control over what happens after form submission. You can handle the submission process within your Livewire component and then choose to display a success message, perform further actions, or redirect the user without the page reloading.
With wire:submit, the default form submission behavior occurs after the Livewire component's method has executed. This means the page may reload or navigate away depending on the form's action attribute or the browser's default behavior. You have less control over the user experience after form submission compared to using wire:submit.prevent.
In summary, wire:submit.prevent provides more control over the form submission process and the user experience after submission, while wire:submit allows the default behavior to occur, potentially resulting in a page reload or navigation. The choice between them depends on your specific requirements and desired user experience.

Form submission using wire:submit and wire:submit.prevent

let's create a simple example using both wire:submit.prevent and wire:submit directives to illustrate their differences. In this example, we'll create a form to submit a message, and after submission, we'll either display a success message or redirect the user to a new page.

First, let's create a Livewire component called MessageForm:

php artisan make:livewire MessageForm
Enter fullscreen mode Exit fullscreen mode

Now, let's define the component logic in

app/Http/Livewire/MessageForm.php
Enter fullscreen mode Exit fullscreen mode

:

// app/Http/Livewire/MessageForm.php

namespace App\Http\Livewire;

use Livewire\Component;
use App\Models\Message;

class MessageForm extends Component
{
    public $message;
    public $successMessage;

    public function render()
    {
        return view('livewire.message-form');
    }

    public function submitWithPrevent()
    {
        // Save the message to the database
        Message::create(['content' => $this->message]);

        // Set success message
        $this->successMessage = 'Message submitted successfully!';
    }

    public function submitWithoutPrevent()
    {
        // Save the message to the database
        Message::create(['content' => $this->message]);

        // Redirect to a new page after form submission
        return redirect()->to('/thank-you');
    }
}
Enter fullscreen mode Exit fullscreen mode

Next, let's create the corresponding view file

resources/views/livewire/message-form.blade.php:
Enter fullscreen mode Exit fullscreen mode
<!-- resources/views/livewire/message-form.blade.php -->

<div>
    @if ($successMessage)
        <div>{{ $successMessage }}</div>
    @endif

    <form wire:submit.prevent="submitWithPrevent">
        <input type="text" wire:model="message" placeholder="Enter your message">
        <button type="submit">Submit with Prevent</button>
    </form>

    <form wire:submit="submitWithoutPrevent">
        <input type="text" wire:model="message" placeholder="Enter your message">
        <button type="submit">Submit without Prevent</button>
    </form>
</div>
Enter fullscreen mode Exit fullscreen mode

In this view file, we have two forms:

The first form uses wire:submit.prevent, which calls the submitWithPrevent method when submitted. After submitting, it displays a success message without reloading the page.
The second form uses wire:submit, which calls the submitWithoutPrevent method when submitted. After submitting, it redirects the user to a new page (/thank-you).
Make sure to define the routes and models as necessary in your Laravel application.

This example demonstrates the difference between using wire:submit.prevent and wire:submit. With wire:submit.prevent, you have control over the submission process and can handle it within the Livewire component, while with wire:submit, the default form submission behavior occurs, and you have less control over the subsequent actions.

How to redirect new page while we use wire:submit.prevent

ou can still redirect the user to a "thank you" page even when using wire:submit.prevent. However, instead of relying on the default form submission behavior, you would need to use JavaScript to perform the redirection after handling the form submission in the Livewire component.

Here's how you can modify the submitWithPrevent method in the MessageForm component to achieve this:

// app/Http/Livewire/MessageForm.php

namespace App\Http\Livewire;

use Livewire\Component;
use App\Models\Message;

class MessageForm extends Component
{
    public $message;
    public $successMessage;

    public function render()
    {
        return view('livewire.message-form');
    }

    public function submitWithPrevent()
    {
        // Save the message to the database
        Message::create(['content' => $this->message]);

        // Set success message
        $this->successMessage = 'Message submitted successfully! Redirecting...';

        // Execute JavaScript to redirect after a brief delay
        $this->dispatchBrowserEvent('redirectAfterSubmit', ['url' => '/thank-you']);
    }
}
Enter fullscreen mode Exit fullscreen mode

In your Livewire view, you need to include the script to handle the browser event:

<!-- resources/views/livewire/message-form.blade.php -->

<div>
    @if ($successMessage)
        <div>{{ $successMessage }}</div>
    @endif

    <form wire:submit.prevent="submitWithPrevent">
        <input type="text" wire:model="message" placeholder="Enter your message">
        <button type="submit">Submit with Prevent</button>
    </form>
</div>

<script>
    document.addEventListener('livewire:load', function () {
        Livewire.on('redirectAfterSubmit', function (data) {
            setTimeout(function () {
                window.location.href = data.url;
            }, 2000); // Redirect after 2 seconds (adjust as needed)
        });
    });
</script>
Enter fullscreen mode Exit fullscreen mode

=========================================================

$(document).on('livewire:load', function () {
    Livewire.on('redirectAfterSubmit', function (data) {
        setTimeout(function () {
            window.location.href = data.url;
        }, 2000); // Redirect after 2 seconds (adjust as needed)
    });
});
Enter fullscreen mode Exit fullscreen mode

In this modification:

After handling the form submission in the submitWithPrevent method, a success message is set.
The Livewire component emits a browser event named redirectAfterSubmit along with the URL where you want to redirect the user.
A JavaScript listener is added to the Livewire component, which listens for the redirectAfterSubmit event. When the event is received, it triggers a redirection to the specified URL after a brief delay.
This approach allows you to redirect the user to a "thank you" page even when using wire:submit.prevent.

wiresubmitprevent

Top comments (0)