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
How to Force Redirect Http to Https in Laravel
How to Force Redirect Http to...

In this small artical we will see how to force redirect http to https in laravel, Here i will show you two method in&nbs...

Read More

Aug-11-2021

How to Change Date Format in Laravel 11
How to Change Date Format in L...

Hello developers! In this article, we'll see how to change the date format in laravel 11. Here, we'll learn...

Read More

Apr-29-2024

Datatables Show And Hide Columns Dynamically In jQuery
Datatables Show And Hide Colum...

In this article, we will see how to hide and show columns in datatable in jquery. This example shows how you can ma...

Read More

Jun-07-2022

How To Count Days Between Two Dates In PHP Excluding Weekends
How To Count Days Between Two...

In this article, we will see how to count days between two dates in PHP excluding weekends. Here, we will learn to...

Read More

Jan-25-2023