Livewire Form Validation: Building Better User Experiences in Laravel (2024)

Forms are an integral part of web applications. It allows users to input data and interact with your website. Whether it’s for user registration, login, or simply providing feedback. However, poorly handled form submissions can result in a frustrating user experience. There are different ways to handle the form validation. Such is through every form submitted, or through real-time form validation. One way to enhance the user experience is through real-time form validation. It provides instant feedback to users as they fill out the form. In this tutorial, we will explore how to achieve this using Laravel Livewire. Laravel Livewire form validation provides an easy way to handle form submission requests. This is a powerful library for building dynamic web interfaces. If you are an absolute beginner in Livewire, then you can follow the Getting Started with Laravel Livewire.

Livewire is a full-stack framework for Laravel that enables developers to build dynamic web interfaces without writing a single line of JavaScript. It simplifies the development process by allowing you to write your front-end logic using PHP and Blade templates. You can use the different form validation techniques. The real-time form interactivity is typically associated with JavaScript frameworks.

Before moving to this example, let’s take a glimpse of the demo application that we are going to build in this post.

Livewire Form Validation: Building Better User Experiences in Laravel (2)

Now, let’s implement the Laravel Livewire form validation.

Before diving into Livewire form validation, make sure you have the following prerequisites in place:

  • Laravel: You should have Laravel installed on your local development environment. If not, then create a new project for this.
  • Composer: Ensure that composer is installed on your system as it’s required for managing Laravel packages.
  • Basic Understanding: Familiarity with Laravel and Blade templates will be helpful.

If you don’t already have a Laravel project, you can create one by running the following command in your terminal.

composer create-project --prefer-dist laravel/laravel livewire-form

It will take a couple of seconds to install. Hence, once you have done so, let’s proceed with the livewire installation in Laravel.

So, next, just navigate to the project directory.

cd livewire-form

Thereafter, we will be installing Livewire in Laravel.

To install the Laravel Livewire package, you will have to hit the below command.

composer require livewire/livewire

This command installs Livewire and its dependencies into your Laravel project.

In order to go ahead with livewire form validation, you required a Livewire component. Hence, you can create it using the below command.

php artisan make:livewire ContactForm

Here, the command will create a component having two files. The one will be a class file and another will be a blade (view) file.

The class file will be located in the app/Http/Livewire directory. If you open that then you will have the below snippet inside it.

<?php

namespace App\Http\Livewire;
use Livewire\Component;class ContactForm extends Component
{
public function render()
{
return view('livewire.contact-form');
}
}

But, the blade file will be located in the resources/views/livewire directory. This will contain an empty div by default as shown below.

<div>
{{-- Close your eyes. Count to one. That is how long forever feels. --}}
</div>

Now, it’s time to design a basic form in which we can apply the Livewire form validation.

Recommended: Advanced Eloquent Relation with hasManyThrough in Laravel 10

At the very first, open the contact-form.blade file available in the resources/views/livewire directory. Thereafter, you will have to add the below snippet for a basic form.

<div class="container my-2">
<div class="row">
<div class="col-xl-6 m-auto">
 {{-- form starts --}}
<form>
<div class="card shadow">
<div class="card-header">
<h4 class="card-title fw-bold">Livewire Form Validation </h4>
</div>
<div class="card-body"> {{-- name --}}
<div class="form-group">
<label for="name">Name</label>
<input type="text" id="name" placeholder="Name" class="form-control">
</div>
{{-- email --}}
<div class="form-group my-3">
<label for="email">Email</label>
<input type="email" id="email" placeholder="Email" class="form-control">
</div>
{{-- message --}}
<div class="form-group my-3">
<label for="message">Message</label>
<textarea id="message" placeholder="Message" class="form-control"></textarea>
</div>
<div class="form-group mb-2">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</div>
</form>
{{-- form ends --}}
</div>
</div>
</div>

I have designed a very basic form to apply the livewire validation over here. Now, let’s include this component in a Laravel blade file.

To include this Livewire form component, I will create a fresh blade file with the name master.blade.php. That will contain the Bootstrap for applying some inbuilt styles.

Therefore, I have created a master blade file and included the Livewire (ContactForm) component.

<!doctype html>
<html lang="en">
<head>
<title>Livewire Form Validation in Laravel</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS v5.2.1 -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-iYQeCzEYFbKjA/T2uDLTpkwGzCiq6soy8tYaI1GyVh/UjpbCx/TYkiZhlZB6+fzT" crossorigin="anonymous">
<!-- Livewire Style -->
@livewireStyles
</head>
<body> <main>
<!-- Include Livewire Component -->
@livewire('contact-form')
</main>
<!-- Livewire Scripts -->
@livewireScripts
</body>
</html>

Now, I have created a route to render this master blade file in order to see the form design.

Route::get('/form', function() {
return view('master');
});

Now, if you run the application and access the above URL in the browser then you will have the below result.

Livewire Form Validation: Building Better User Experiences in Laravel (3)

Next, you will have to handle the form data in order to validate it. So, let’s do it.

So, at very first you will have to capture the inputs from the form. Hence, to achieve this, Livewire provides a data binding feature through which you can read out the form inputs.

Also, the form needs to be submitted. Hence, for this, Livewire provides a form submit event for handling form submission.

The syntax is shown below.

wire:model="inputName" // for capturing input value
wire:submit="YourFunctionName" // for handling form submitwire:submit.prevent="YourFunctionName" // for handling form submit without refresh

Here, as per the form we have created, you have to add the data binding property in each input except the button. Hence, let’s do that quickly.

<div class="container my-2">
<div class="row">
<div class="col-xl-6 m-auto">
 {{-- form starts --}}
<form wire:submit.prevent="submitForm">
<div class="card shadow">
<div class="card-header">
<h4 class="card-title fw-bold">Livewire Form Validation </h4>
</div>
<div class="card-body"> {{-- name --}}
<div class="form-group">
<label for="name">Name</label>
<input type="text" id="name" wire:model="name" placeholder="Name" class="form-control">
</div>
{{-- email --}}
<div class="form-group my-3">
<label for="email">Email</label>
<input type="text" id="email" wire:model="email" placeholder="Email" class="form-control">
</div>
{{-- message --}}
<div class="form-group my-3">
<label for="message">Message</label>
<textarea id="message" wire:model="message" placeholder="Message" class="form-control"></textarea>
</div>
<div class="form-group mb-2">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</div>
</form>
{{-- form ends --}}
</div>
</div>
</div>

Now, in order to handle the form submit event and validation, you will have to create the functionality in its respective php file (component).

After adding the form-handling event, the Component class will become as shown below.

<?php
namespace App\Http\Livewire;use Livewire\Component;class ContactForm extends Component
{
// Define form input properties
public $name, $email, $message;
public function render()
{
return view('livewire.contact-form');
}
// Form Submit Function
public function submitForm() {
// Form validation rules
$this->validate([
'name' => 'required|min:5',
'email' => 'required|email',
'message' => 'required|min:10|max:100'
]);
}
}

Here, in the submit function, I have defined the validation rules for the inputs. You can refer to the Laravel form Validation for more rules.

After defining the form validation rule, you will have to display the validation error messages across each input field.

Hence, let’s do that in the component view.

The validation error message can be displayed in the same way as you do in Laravel Blade. The syntax is below.

@error('inputName')
<span class="text-danger">{{ $message }}</span>
@enderror

So, let’s add this validation error message next to all inputs.

<div class="container my-2">
<div class="row">
<div class="col-xl-6 m-auto">
 {{-- form starts --}}
<form wire:submit.prevent="submitForm">
<div class="card shadow">
<div class="card-header">
<h4 class="card-title fw-bold">Livewire Form Validation </h4>
</div>
<div class="card-body"> {{-- name --}}
<div class="form-group">
<label for="name">Name</label>
<input type="text" id="name" wire:model="name" placeholder="Name" aria-describedby="name-error" aria-required="true" @error('name') aria-invalid="true" @enderror class="form-control @error('name') is-invalid @enderror">
{{-- Display name validation error message --}}
@error('name')
<span id="name-error" class="text-danger">{{ $message }}</span>
@enderror
</div>
{{-- email --}}
<div class="form-group my-3">
<label for="email">Email</label>
<input type="text" id="email" wire:model="email" placeholder="Email" aria-describedby="email-error" @error('email') aria-invalid="true" @enderror class="form-control @error('email') is-invalid @enderror">
{{-- Display email validation error message --}}
@error('email')
<span id="email-error" class="text-danger">{{ $message }}</span>
@enderror
</div>
{{-- message --}}
<div class="form-group my-3">
<label for="message">Message</label>
<textarea id="message" wire:model="message" placeholder="Message" aria-describedby="message-error" @error('message') aria-invalid="true" @enderror class="form-control @error('message') is-invalid @enderror"></textarea>
{{-- Display message validation error message --}}
@error('message')
<span id="message-error" class="text-danger">{{ $message }}</span>
@enderror
</div>
<div class="form-group mb-2">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</div>
</form>
{{-- form ends --}}
</div>
</div>
</div>

Now, refresh the browser and submit the form to check the validation error message.

Read full article here —
https://programmingfields.com/livewire-form-validation-building-better-user-experiences-in-laravel/

Livewire Form Validation: Building Better User Experiences in Laravel (2024)
Top Articles
Latest Posts
Article information

Author: Ray Christiansen

Last Updated:

Views: 6323

Rating: 4.9 / 5 (69 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Ray Christiansen

Birthday: 1998-05-04

Address: Apt. 814 34339 Sauer Islands, Hirtheville, GA 02446-8771

Phone: +337636892828

Job: Lead Hospitality Designer

Hobby: Urban exploration, Tai chi, Lockpicking, Fashion, Gunsmithing, Pottery, Geocaching

Introduction: My name is Ray Christiansen, I am a fair, good, cute, gentle, vast, glamorous, excited person who loves writing and wants to share my knowledge and understanding with you.