Laravel 10 Ajax Form Validation Example

Laravel 10 Ajax form validation allows you to implement real-time validation for form inputs, providing an improved user experience and ensuring data integrity. Here’s a step-by-step guide on how to validate Laravel forms using Ajax.

With Ajax form validation in Laravel, you can validate form inputs without reloading the entire page, reducing user frustration and improving data accuracy. Here’s how you can implement Ajax form validation in Laravel stepy by step example.

#1 Install Laravel App

First, you need to install a fresh Laravel application using the following command:

composer create-project --prefer-dist laravel/laravel laravel-app

Next, go inside the app directory

cd laravel-app

#2 Setup Database Credential

Next, open the .env file which is located in your project root directory and update your database credential such as database name, username, password or your DB.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db name
DB_USERNAME=db user name
DB_PASSWORD=db password

#3 Make Model and Migration

Now generate a model and migration file by just adding the below command in your terminal which generates a model file and migration which will show your database table after running the migration command.

php artisan make:model Contact -m

After this open the newly created file database\migrations\2020_09_14_120412_create_contacts_table.php and add the below code on it.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateContactsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('contacts', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email');
            $table->string('mobile');
            $table->string('subject');
            $table->text('message');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('contacts');
    }
}

Next, we need to run the migrate command to generate database tables. So open your terminal and run the below command.

php artisan migrate

Next, open the app\Models\Contact.php file and add fillable properties in your contact model.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Contact extends Model
{
    use HasFactory;

    protected $fillable = [
      'name', 'email', 'mobile', 'subject', 'message'
    ];
}

#4 Add Routes

Now, open the routes/web.php file and add two routes for implementing the Laravel 10 Ajax Form Validation. One route will show the form and another is to save the data to the database using ajax request.

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ContactController;

Route::get('contact-us', [ ContactController::class, 'create' ]);
Route::post('contact-us', [ ContactController::class, 'store' ]);


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

#5 Create New Controller

Now, create a new controller in your application using the following command in your terminal.

php artisan make:controller ContactController

After getting the new controller, open the app/Http/Controllers/ContactController.php file and update the below code on it.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Contact;

class ContactController extends Controller
{
    public function create()
    {

      return view('contacts');
    }

   public function store(Request $request)
   {
        
        $request->validate([
            'name'      => 'required',
            'email'     => 'required',
            'mobile'    => 'required',
            'message'   => 'required',
        ]);

        Contact::create([
            'name'     => $request->name,
            'email'    => $request->email,
            'mobile'   => $request->mobile,
            'message'  => $request->message,
        ]);

      return response()->json([ 'success'=> 'Your request successfully submitted!']);

  }
}

#6 Create Blade File

Next, create a new blade file named contacts.blade.php, which shows the form where we send the ajax request for showing form validations and etc functionalities. So, open the resources\views\contacts.blade.php file and update the below code on it

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
    <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <meta name="csrf-token" content="{{ csrf_token() }}" />
</head>

<body>
    <div class="container">
        <h1>Laravel 10 Ajax Form Validation</h1>
          <span class="success" style="color:green; margin-top:10px; margin-bottom: 10px;"></span>
        <form id="contact-form">
            <div class="form-group">
                <label>Name:</label>
                <input type="text" name="name" class="form-control" placeholder="Enter Name">
                <span class="text-danger" id="nameError"></span>
            </div>

            <div class="form-group">
                <label>Email:</label>
                <input type="email" name="email" class="form-control" placeholder="Enter Email">
                <span class="text-danger" id="emailError"></span>
            </div>

            <div class="form-group">
                <strong>Mobile Number:</strong>
                <input type="text" name="mobile" class="form-control" placeholder="Enter Mobile">
                <span class="text-danger" id="mobileError"></span>
            </div>
            <div class="form-group">
                <strong>Message:</strong>
                <input type="text" name="message" class="form-control" placeholder="Enter Your Message">
                <span class="text-danger" id="messageError"></span>
            </div>
            <div class="form-group">
                <button class="btn btn-success save-data">Save</button>
            </div>
        </form>
    </div>
</body>
</html>

#7 Send Ajax Request

After creating the blade file now add the ajax jquery code after the last closing div of your blade file and send the post request to your controller via ajax. Here we are using the jQuery submit function and use the CSRF for send request.

<script>

  $('#contact-form').on('submit', function(event){
      event.preventDefault();

      let name = $("input[name=name]").val();
      let email = $("input[name=email]").val();
      let mobile = $("input[name=mobile]").val();
      let message = $("input[name=message]").val();
      let _token   = $('meta[name="csrf-token"]').attr('content');

      $.ajax({
        url: "/contacts",
        type:"POST",
        data:{
          name:name,
          email:email,
          mobile:mobile,
          message:message,
          _token: _token
        },
        success:function(response){
          console.log(response);
          if(response) {
            $('.success').text(response.success);
            $("#contact-form")[0].reset();
          }
        },
        error: function(error) {
         console.log(error);
          $('#nameError').text(response.responseJSON.errors.name);
          $('#emailError').text(response.responseJSON.errors.email);
          $('#mobileError').text(response.responseJSON.errors.mobile);
          $('#messageError').text(response.responseJSON.errors.message);
        }
       });
  });
</script>

1 thought on “Laravel 10 Ajax Form Validation Example”

Leave a Comment