Laravel 11 Livewire Form Validation Example

Websolutionstuff | Jun-12-2024 | Categories : Laravel

Hello, laravel web developers! In this article, we'll see how to validate forms in laravel 11 Livewire. In laravel 11 Livewire, we'll validate the form without page refresh. To avoid storing incomplete or dangerous user input, most forms need some sort of input validation.

Livewire makes validating your forms as simple as adding #[Validate] attributes above the properties you want to be validated.

Once a property has a #[Validate] attribute attached to it, the validation rule will be applied to the property's value any time it's updated server-side.

Laravel 11 Livewire Form Validation Example

Laravel 11 Livewire Form Validation Example

 

Step 1: Install Laravel 11 Application

In this step, we'll install 11 applications using the following command.

composer create-project laravel/laravel example-app

 

Step 2: Create Migration and Model

Next, we'll create migration and model using the following command.

php artisan make:migration create_contacts_table

Migration:

<?php
  
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
  
return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up(): void
    {
        Schema::create('contacts', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email');
            $table->text('body');
            $table->timestamps();
        });
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down(): void
    {
        Schema::dropIfExists('products');
    }
};

Then, run the following command to migrate the table into the database.

php artisan migrate

Next, we'll create a Contact model by using the following command.

php artisan make:model Contact

App/Models/Contact.php

<?php
  
namespace App\Models;
  
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
  
class Contact extends Model
{
    use HasFactory;
  
    /**
     * Write code on Method
     *
     * @return response()
     */
    protected $fillable = [
        'name', 'email', 'body'
    ];
}

 

 

Step 3: Install Livewire

Next, we'll install Livewire using the following command.

composer require livewire/livewire

 

Step 4: Create Component

Then, we'll create a Livewire ContactForm component using the following command.

php artisan make:livewire contact-form

This command generates two files.

app/Livewire/ContactForm.php

resources/views/livewire/contact-form.blade.php

app/Livewire/ContactForm.php

<?php
  
namespace App\Livewire;
  
use Livewire\Component;
use App\Models\Contact;
  
class ContactForm extends Component
{
    public $name;
    public $email;
    public $body;
  	  
  	/**
     * Write code on Method
     *
     * @return response()
     */
    public function submit()
    {
        $validatedData = $this->validate([
            'name' => 'required|min:6',
            'email' => 'required|email',
            'body' => 'required',
        ]);
  
        Contact::create($validatedData);
  
        return redirect()->to('/form');
    }
   
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function render()
    {
        return view('livewire.contact-form');
    }
}

resources/views/livewire/contact-form.blade.php

<form wire:submit.prevent="submit">
    <div class="form-group">
        <label for="exampleInputName">Name</label>
        <input type="text" class="form-control" id="exampleInputName" placeholder="Enter name" wire:model="name">
        @error('name') <span class="text-danger">{{ $message }}</span> @enderror
    </div>
  
    <div class="form-group">
        <label for="exampleInputEmail">Email</label>
        <input type="text" class="form-control" id="exampleInputEmail" placeholder="Enter name" wire:model="email">
        @error('email') <span class="text-danger">{{ $message }}</span> @enderror
    </div>
  
    <div class="form-group">
        <label for="exampleInputbody">Body</label>
        <textarea class="form-control" id="exampleInputbody" placeholder="Enter Body" wire:model="body"></textarea>
        @error('body') <span class="text-danger">{{ $message }}</span> @enderror
    </div>
  
    <button type="submit" class="btn btn-primary">Save Contact</button>
</form>

 

Step 5: Define Route

Now, define the routes into the web.php file

routes/web.php

<?php

use Illuminate\Support\Facades\Route;

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

 

Step 6: Create View File

Then, we'll create a Blade file and use @livewireStyles, @livewireScripts, and @livewire('contact-form').

resources/views/form.blade.php

<!DOCTYPE html>
<html>
<head>
    <title></title>
    @livewireStyles
    <link rel="stylesheet" href="{{ asset('css/app.css') }}">
</head>
<body>
  
<div class="container">
  
    <div class="card mt-5">
      <div class="card-header">
        Laravel 11 Livewire Form Validation Example - Websolutionstuff
      </div>
      <div class="card-body">
        @livewire('contact-form')
      </div>
    </div>
      
</div>
  
</body>
<script src="{{ asset('js/app.js') }}"></script>
@livewireScripts
</html>

 

Step 7: Run the Laravel 11 Application

Now, run the laravel 11 application using the following command.

php artisan serve

 


You might also like:

Recommended Post
Featured Post
Server Side Custom Search in Datatables
Server Side Custom Search in D...

In this example we will discuss about server side custom search in datatable. Datatable provides default searching...

Read More

Apr-05-2021

Laravel 9 File Upload Example
Laravel 9 File Upload Example

In this artical, we will explain the laravel 9 file upload example step by step. As we know file upload is the most comm...

Read More

Mar-11-2022

Node.js Express CRUD Example with MySQL
Node.js Express CRUD Example w...

Hello Guys, In this tutorial we will see how to perform Node js Express CRUD example with mysql. Node js Express ...

Read More

Aug-02-2021

How to Generate Fake Data using Tinker in Laravel 11
How to Generate Fake Data usin...

Hello, laravel web developers! In this article, we'll see how to generate fake data using Tinker in laravel 11....

Read More

May-22-2024