Form validation is a crucial part of building secure and user-friendly web applications. With Laravel 11 and Livewire 3, you can implement dynamic, real-time form validation effortlessly.
Whether you need to validate inputs on the fly or customize validation rules, Livewire makes it simple and powerful.
In this guide, I’ll show you how to set up form validation in Livewire 3 step by step.
Form Validation Laravel Livewire 3
In this step, we'll create a Livewire component using their command.
php artisan make:livewire ProductCreate
app/Livewire/ProductCreate.php
resources/views/livewire/product-create.blade.php
Now, both files we will update.
app/Livewire/ProductCreate.php
<?php
namespace App\Livewire;
use Livewire\Component;
use App\Models\Product;
class ProductCreate extends Component
{
public $name, $price, $detail;
public function render()
{
return view('livewire.product-create');
}
/**
* Write code on Method
*
* @return response()
*/
public function submit()
{
$this->validate([
"name" => "required",
"price" => "requierd|min:5|numeric",
"detail" => "required"
]);
$product = Product::create([
"name" => $this->name,
"price" => $this->price,
"detail" => $this->detail
]);
info($product);
}
}
resources/views/livewire/product-create.blade.php
<div>
<form wire:submit="submit">
<label>Name:</label>
<input type="text" name="name" class="form-control" wire:model.change="name">
@error("name")
<p class="text-danger">{{ $message }}</p>
@enderror
<label>Price:</label>
<input type="text" name="price" class="form-control" wire:model="price">
@error("price")
<p class="text-danger">{{ $message }}</p>
@enderror
<label class="mt-1">Detail:</label>
<textarea class="form-control" wire:model="detail"></textarea>
@error("detail")
<p class="text-danger">{{ $message }}</p>
@enderror
<button class="btn btn-success mt-3" wire:loading.attr="disabled" type="submit">Submit</button>
</form>
</div>
Now, we'll use the Product component on the home page.
resources/views/home.blade.php
@extends('layouts.app')
@section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">{{ __('Product Create') }}</div>
<div class="card-body">
<livewire:product-create />
</div>
</div>
</div>
</div>
</div>
@endsection
You might also like:
In this article, we will see an example of laravel 8 custom email verification. Many web applications require users...
Dec-29-2021
Have you ever seen those pop-up boxes on websites? They're called modal forms, and they make it easier to do things...
Jan-04-2023
In this tutorial, I will let you know how to use summernote editor in laravel, In laravel or PHP many editors are a...
Jun-17-2020
Imagine this: You've made a super cool website, and now you want to make sure only the right people can use it. That...
Jan-03-2023