Form Handling and Validation in Livewire 3.0

Form Handling and Validation in Livewire 3.0

Step 1: Creating the Livewire Component

We’ll start by creating a new component for managing a simple user registration form:


php artisan make:livewire RegisterUser

This command will generate the following files:

  1. app/Livewire/RegisterUser.php – The PHP class for the component logic.

  2. resources/views/livewire/register-user.blade.php – The Blade file for the form UI.

Step 2: Setting Up the Component Logic

Open the RegisterUser.php file and define the properties for your form fields:


<?php

namespace App\Livewire;

use Livewire\Component;

class RegisterUser extends Component
{
    public $name;
    public $email;
    public $password;

    protected $rules = [
        'name' => 'required|min:3',
        'email' => 'required|email',
        'password' => 'required|min:6',
    ];

    public function updated($propertyName)
    {
        $this->validateOnly($propertyName);
    }

    public function register()
    {
        $this->validate();

        // Logic to register the user
        // For example: User::create([...])

        session()->flash('success', 'User registered successfully!');

        // Reset the form fields
        $this->reset(['name', 'email', 'password']);
    }

    public function render()
    {
        return view('livewire.register-user');
    }
}

Key Points:

  1. $rules: Defines the validation rules for the form fields.

  2. validateOnly($propertyName): Validates a single field in real-time when it is updated.

  3. register(): Validates all fields and handles form submission logic.

  4. reset(): Clears the form fields after successful submission.

Step 3: Building the Form UI

Open the register-user.blade.php file and create the form structure:


<div>
    @if (session()->has('success'))
        <div class="alert alert-success">
            {{ session('success') }}
        </div>
    @endif

    <form wire:submit.prevent="register">
        <div>
            <label for="name">Name</label>
            <input type="text" id="name" wire:model="name">
            @error('name') <span class="error">{{ $message }}</span> @enderror
        </div>

        <div>
            <label for="email">Email</label>
            <input type="email" id="email" wire:model="email">
            @error('email') <span class="error">{{ $message }}</span> @enderror
        </div>

        <div>
            <label for="password">Password</label>
            <input type="password" id="password" wire:model="password">
            @error('password') <span class="error">{{ $message }}</span> @enderror
        </div>

        <button type="submit">Register</button>
    </form>
</div>

What’s Happening Here?

  1. wire:model: Binds the input fields to the Livewire component properties.

  2. @error: Displays validation error messages dynamically.

  3. wire:submit.prevent: Prevents the default form submission and triggers the register() method.

Step 4: Real-Time Validation

Real-time validation is achieved using the updated() method in the component. As users type in the fields, Livewire validates the input and updates the error messages dynamically without refreshing the page.

Example:

If the user enters an invalid email, the error message will be displayed immediately under the email input field.

Step 5: Handling Success Messages

In the register() method, we use Laravel’s session flash messages to notify users of successful registration. The message is displayed dynamically using:


@if (session()->has('success'))
    <div class="alert alert-success">
        {{ session('success') }}
    </div>
@endif

This enhances the user experience by providing instant feedback.

Final Output

With the above setup, visiting the page with the RegisterUser component allows users to:

  1. Enter their name, email, and password.

  2. See real-time validation error messages if they leave fields empty or provide invalid input.

  3. Successfully submit the form and see a success message.

  4. Have the form fields cleared after successful submission.


© Copyright 2025 Wontonee. All Right Reserved.

×How can I help you?