How To Validate Form Via Ajax In Laravel

This is a short guide on laravel 8 ajax form validation example. Here you will learn laravel 8 jquery ajax post validation. let’s discuss about laravel 8 ajax show validation errors. let’s discuss about ajax validation in laravel 8.

Form validation is a basic requirement of any form. we should implement validation even if you use ajax or simple form. But if you are working with jquery ajax then you can use also server side validation using laravel and display error messages on front side.

You can simply use laravel 8 validation like required, email, same, unique, date, integer etc using jquery ajax post, get, put or delete request. we will use Validator make function for create validation and check using passes() function.

In this example i will show you how to use laravel default validation with jquery ajax. Here we also print laravel validation message when false. So if you want to ajax form validation in laravel app then you are right place.

Just follow bellow step to create an ajax validation example:

Step 1: Add Route

Route::prefix('category')->middleware('auth','acl')->group(function() {
    Route::get('/' ,'[email protected]')->name('category.index');
    Route::post('category/store', '[email protected]')-     
    >name('category.store');
});

Step 2: Create Controller

In this point, now we should create new controller as CategoryController. So run bellow command and create new controller.

php artisan make:controller CategoryController

After bellow command, you will find a new file in this path app/Http/Controllers/CategoryController.php.

In this controller we will write three methods for ajax view and post as listed below methods:

  1. index()

2. store()

So, let’s copy bellow code and put on the CategoryController.php file

app/Http/Controllers/CategoryController.php

<?php

namespace Modules\Knowledgebase\Http\Controllers;

use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\Knowledgebase\Entities\Category;

class CategoryController extends Controller
{
    /**
     * Display a listing of the resource.
     * @return Renderable
     */
    public function index()
    {
        $categories = Category::get();
        return view('knowledgebase::category.index', compact('categories'));
    }
   
    /**
     * Store a newly created resource in storage.
     * @param Request $request
     * @return Renderable
     */
    public function store(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'name' => 'required|regex:/^[\pL\s\-\w.]+$/u|min:3|max:100',
        ],
            [
                'required' => 'Category :attribute is required.',
            ]);
        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'errors' => $validator->getMessageBag()->toArray(),
            ]);
        }
        Category::create($request->all());
        $data = [
            'data_saved' => true,
        ];
        return response()->json($data);
    }
}

Step 3: Index View File

In Last step, let’s create myform.blade.php(resources/views/myform.blade.php) for layout and we will write design code and jquery ajax code,so put following code:

resources/views/myform.blade.php

@extends('admin.layouts.app')
@section('title', __('knowledgebase::lang.category'))
@section('content')

    <div class="app-main__inner">
        <div class="row mb-2 mb-xl-3">
            <div class="col-auto d-none d-sm-block">
                <h3>{{ __('global-lang.knowledgebase-category') }}</h3>
                <hr>
            </div>
            <div class="col-auto ms-auto text-end mt-n1">
                <button type="button" class="render-create btn btn-primary btn-
                       shadow" >
                    <i class="fa fa-plus" aria-hidden="true"></i>
                    {{ __('knowledgebase::lang.create-category') }}</button>
            </div>
        </div>
        <div class="row">
            <div class="col-md-12">
                <div class="main-card mb-3 card">
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-striped table-bordered"                
                             id="dataTable" width="100%" cellspacing="0">
                                <thead>
                                    <tr>
                                        <th>{{ __('knowledgebase::lang.title') 
                                         }}</th>
                                        <th>{{ 
                                          __('knowledgebase::lang.description') 
                                        }}</th>
                                        <th>{{ __('knowledgebase::lang.action') 
                                        }}</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @isset($categories)
                                        @foreach ($categories as $key => 
                                          $category)
                                            <tr>
                                                <td>{{ $category->name }}</td>
                                                <td>{{ 
                                                  substr(strip_tags($category-     
                                                  >description), 0, 50) }}</td                                                   
                                            </tr>
                                        @endforeach
                                    @endisset
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    @push('scripts')
        <script>
            $(document).on('click', '.delete-category', function() {
                swal({
                        title: "{{ __('global-lang.are-you-sure') }}",
                        text: "{{ __('knowledgebase::lang.not-recover') }}",
                        icon: "warning",
                        buttons: true,
                        dangerMode: true,
                    })
                    .then((willDelete) => {
                        if (willDelete) {
                            id = $(this).attr('id');
                            var url = '{{ route('category.destroy', ':id') }}';
                            url = url.replace(':id', id);
                            $.ajax({
                                type: "post",
                                url: url,
                                data: {
                                    '_token': "{{ csrf_token() }}"
                                },
                                success: function(data) {
                                    swal("{{ __('knowledgebase::lang.category-
                                      deleted') }}", {
                                        icon: "success",
                                    });
                                    location.reload();
                                },
                                error: function(data) {
                                    swal("{{ __('global-lang.something-went-
                                     wrong') }}", {
                                        icon: "warning",
                                    });
                                },
                            });
                        } else {
                            swal("{{ __('knowledgebase::lang.category-not-
                              deleted') }}");
                        }
                    });
            });


            $(document).on('click', '.render-create', function() {              
                $("#open-create-modal").modal('show')
                $(".name-msg").hide();
                $(".name").removeClass("is-invalid");                    
            });

            //store script for category
            $(".submit-form").click(function(e) {
                e.preventDefault();
                var name = $("input[name='name']").val();
                var description = $('.category-description').val();
                var data = {
                    name: name,
                    description: description
                };
                axios({
                        url: "{{ route('category.store') }}",
                        method: 'POST',
                        data: data,
                    })
                    .then(function(response) {
                        if (response.data.success == false) {
                            $.each(response.data.errors, function(key, value) {
                                $('.' + key).addClass("is-invalid");
                                $('.' + key).html('');
                                $('.' + key).append('<span class="text-danger">' 
                                   + value[0] + '</span>');
                                $(".name-msg").show();
                            });
                        } else if (response.data.data_saved == true) {
                            location.reload();
                        }
                    })
            });

      </script>
    @endpush
@endsection

Now we are ready to run our example so run the bellow command for a quick run:

php artisan serve

Now you can open bellow URL on your browser:

http://localhost:8000

0 0 votes
Article Rating

Do you want to hire us for your Project Work? Then Contact US.
Spread the love
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x