Laravel 8 Ajax With Validation Example

By : phpicoder Created : February 25, 2021

Hello Developer, In this tutorial, we will learn how to submit ajax form with validation example in laravel 8. This article will give you simple example of ajex submit post form with validation using laravel applications. i explained simply step by step laravel 8 jquery ajax form submit with validation.

many developers face issue for submit ajax form with validation using laravel 8 app, if you have a issue for validation are you right place.

So just follow below steps to create ajax validation example using laravel 8 app.

Preview : "laravel 8 ajax with validation example"
Laravel 8 Ajax With Validation Example

 Step 1: Add Route

First step we need to 2 routes so open your routes/web.php file and add following route. 

<?php

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

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('user-form', [UserController::class, 'userform']);
Route::post('storeUser', [UserController::class, 'storeUser'])->name('storeUser');

Step 2: Create Controller

Now we need to "UserController" controller, So run bellow command and create new "UserController" controller. 

php artisan make:controller UserController 

Now go to app/Http/Controllers/ path and opne UserController.php file and then add following below code.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Validator;

class UserController extends Controller
{
    public function userform()
    {
    	return view('userform');
    }

    public function storeUser(Request $request)
    {
     
    	$validator = Validator::make($request->all(), [
            'name' => 'required',
            'email' => 'required|email',
            'address' => 'required',
        ]);
     
        if ($validator->passes()) {
            return response()->json(['success'=>'Added new records.']);
        }
     
        return response()->json(['error'=>$validator->errors()->all()]);
    }
}

Step 3: Create View File

in this step we need view file, So go to resources/views/ this path and create new file name userform.blade.php and then put following code: 

resources/views/userform.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>laravel 8 ajax with validation example - phpicoder.com</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
</head>
<body>
       
<div class="container">
    <h2>laravel 8 ajax with validation example - phpicoder.com</h2>
       
    <div class="alert alert-danger print-error-msg" style="display:none">
        <ul></ul>
    </div>
       
    <form id="AddUser">
        {{ csrf_field() }}
        <div class="form-group">
            <label>Full Name:</label>
            <input type="text" name="name" class="form-control" placeholder="Full Name">
        </div>
       
        <div class="form-group">
            <strong>Email:</strong>
            <input type="text" name="email" class="form-control" placeholder="Email">
        </div>
       
        <div class="form-group">
            <strong>Address:</strong>
            <textarea class="form-control" name="address" placeholder="Address"></textarea>
        </div>
       
        <div class="form-group">
            <button class="btn btn-success">Submit</button>
        </div>
    </form>
</div>
       
<script type="text/javascript">

    $(document).ready(function() {
        $("body").on("submit", "#AddUser", function (event) {
            event.preventDefault();

            $.ajax({
                type: "POST",
                url: '{!!route('storeUser')!!}',
                data:new FormData(this),
                dataType:'JSON',
                contentType: false,
                cache: false,
                processData: false,
                success: function (data) {
                    if($.isEmptyObject(data.error)){
                        alert(data.success);
                    }else{
                        printErrorMsg(data.error);
                    }
                }
            });
        }); 
       
        function printErrorMsg (msg) {
            $(".print-error-msg").find("ul").html('');
            $(".print-error-msg").css('display','block');
            $.each( msg, function( key, value ) {
                $(".print-error-msg").find("ul").append('<li>'+value+'</li>');
            });
        }
    });
    
</script>

</body>
</html>

Step 4: Run Laravel App

Now we are ready to run our laravel 8 ajax with validation example so run bellow command for quick run: 

php artisan serve

Now you can open bellow URL on your browser:

http://localhost:8000/my-form

I hope it can help you for laravel 8 ajax with validation example...