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:
app/Livewire/RegisterUser.php
– The PHP class for the component logic.
resources/views/livewire/register-user.blade.php
– The Blade file for the form UI.
Open the RegisterUser.php
file and define the properties for your form fields:
'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');
}
}
$rules
: Defines the validation rules for the form fields.
validateOnly($propertyName)
: Validates a single field in real-time when it is updated.
register()
: Validates all fields and handles form submission logic.
reset()
: Clears the form fields after successful submission.
Open the register-user.blade.php
file and create the form structure:
@if (session()->has('success'))
{{ session('success') }}
@endif
wire:model
: Binds the input fields to the Livewire component properties.
@error
: Displays validation error messages dynamically.
wire:submit.prevent
: Prevents the default form submission and triggers the register()
method.
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.
If the user enters an invalid email, the error message will be displayed immediately under the email input field.
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'))
{{ session('success') }}
@endif
This enhances the user experience by providing instant feedback.
With the above setup, visiting the page with the RegisterUser
component allows users to:
Enter their name, email, and password.
See real-time validation error messages if they leave fields empty or provide invalid input.
Successfully submit the form and see a success message.
Have the form fields cleared after successful submission.
410 C, Jaina Tower-1, District Center, Janak Puri New Delhi-110058, India.
© Copyright 2025 Wontonee. All Right Reserved.