Laravel 8.0 Ajax Form Validation Example

Today we will make ajax form validation, so that we can make our form validation without refreshing web page. so, let’s start…

Our Final Output

"ajax form validation in laravel 7" "laravel 7 ajax form submit with validation" "laravel ajax crud with validation" "laravel ajax form submit with validation example" "laravel form validation before submit" "form submit using ajax in laravel with validation" "laravel ajax redirect with message" "laravel ajax error handling"

Create a Laravel new project, run this command 

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

Make Database connection

Go to the .env file and set the database name that you create in your MySQL dashboard admin panel

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_ajax_blog
DB_USERNAME=root
DB_PASSWORD=

Create our custom route

routes/web.php

Route::get('post/create', [PostController::class, 'postCreateByAjax'])
    ->name('post.validation');
Route::post('post/store', [PostController::class, 'postStoreByAjax'])
    ->name('post.validation.store');

Create Model

we will create Post model, run this command

php artisan make:model Post

Models/Post.php
<?php

namespace App\Models;

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

class Post extends Model
{
    use HasFactory;
    protected $fillable = [
        'title',
        'description'
    ];

}

Create Controller

we will create controller named PostController, run this command

php artisan make:controller PostController

app/Http/Controllers/PostController.php
<?php

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class PostController extends Controller
{

    public function postCreateByAjax(){
        return view('ajax.ajax-create');
    }

    public function postStoreByAjax(Request $request){

        $validator = Validator::make($request->all(), [
            'title' => 'required',
            'description' => 'required',
        ]);

        if ($validator->passes()) {

            Post::create($request->all()); // it store data to the DB

            return response()->json(['success'=>'Added new records.']);

        }

        return response()->json(['error'=>$validator->errors()]);

    }
}

Make Migration file

php artisan make:migration create_post_table –create=posts

database/migration/2020_09_20_163428_create_post_table.php
<?php

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

class CreatePostTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->text('title');
            $table->text('description');
            $table->timestamps();
        });
    }

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

Complete migration, run this command

php artisan migrate

Create views

resources/views/add_record.php
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Ajax Validation Laravel 8</title>
    <meta name="_token" content="{{ csrf_token() }}">

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
    <div class="row mt-5">
        <div class="col-md-8 offset-md-2">
            <div class="row">
                <div class="col-md-12 text-center">
                    <h4>Laravel 8 Ajax From Validation Tutorial</h4>
                </div>


                    <div class="col-md-12">
                        <div class="card">
                           <div class="card-body">
                               <div class="card-title">
                                   Create a New Record
                               </div>
                               <div class="body">
                                   <form id="post-form">
                                       @csrf
                                       <div class="form-group">
                                           <label for="title">Title:</label>
                                           <input
                                               type="text"
                                               class="form-control title_err"
                                               id="title"
                                               name="title"
                                               placeholder="Title">
                                           <span class="text-danger error-text title_err"></span>

                                       </div>
                                       <span>Description:</span>
                                       <div class="form-group">
                            <textarea
                                rows="6"
                                class="form-control"
                                id="description"
                                name="description">
                            </textarea>
                                           <span class="text-danger error-text description_err"></span>
                                       </div>
                                       <button type="submit" class="btn btn-primary btn-submit">Add Record</button>
                                   </form>
                               </div>
                           </div>

                    </div>
                </div>

            </div>
        </div>
    </div>
</div>

<script type="text/javascript">

    $(document).ready(function() {

        $(".btn-submit").click(function(e){

            $.ajaxSetup({
                headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content') }
            });
            e.preventDefault();


            var _token = $("input[name='_token']").val();
            var title = $("#title").val();
            var des = $("#description").val();

            //alert(title + " " + des);

            $.ajax({
                url: "{{ route('post.validation.store') }}",
                type:'POST',
                data: {_token:_token, title:title, description:des},
                success: function(data) {
                    //alert("done")
                    console.log(data.error)
                    if($.isEmptyObject(data.error)){
                        alert(data.success);
                        document.getElementById("post-form").reset();
                    }else{
                        printErrorMsg(data.error);
                    }
                }
            });
        });

        function printErrorMsg (msg) {
            $.each( msg, function( key, value ) {
                console.log(key);
                $('.'+key+'_err').text(value);
            });
        }
    });
</script>

</body>
</html>

Output

"ajax form validation in laravel 7" "laravel 7 ajax form submit with validation" "laravel ajax crud with validation" "laravel ajax form submit with validation example" "laravel form validation before submit" "form submit using ajax in laravel with validation" "laravel ajax redirect with message" "laravel ajax error handling"

I think, it will help you!