Ajax Form Validation Example using LARAVEL 10

Spread the love

Hello Guys,

In this article, we will explore the power of Ajax Form Validation with a focus on Laravel 10. This tutorial will guide you through the process of effortlessly submitting an Ajax form while ensuring validation using Laravel 10. We’ll delve into the intricacies of Laravel 10 jQuery Ajax post validation, providing you with a comprehensive understanding.

Ajax Form Validation is an essential technique for any PHP project, as it allows us to seamlessly store data in the database without the need to refresh the webpage. This functionality is made possible through Ajax requests, particularly those initiated by jQuery. If you’re working with Laravel 10 and need to create and submit an Ajax form, this guide will walk you through the process of transferring data via an Ajax request to the controller.

In this example, we’ll create a “posts” table with title and body columns, where each post’s data will be displayed. Additionally, we’ll implement a “Create” button using a jQuery Ajax call, enabling you to generate new posts with ease. The integration of a Bootstrap modal will further enhance your ability to initiate Ajax post requests.

Let’s dive into the complete Ajax Form Validation example by following the step-by-step instructions below. Elevate your web development skills with this informative tutorial.

Step 1: Install Laravel 10

While it’s not mandatory, you can still go ahead and execute the following command if you haven’t yet established your Laravel application:

Also Read: How to Create Custom Helper Functions in LARAVEL 10

composer create-project laravel/laravel example-app

Step 2: Create Migration and Model

Next, let’s create a migration for the “posts” table. You can utilize the following command to modify the code.

php artisan make:migration create_posts_table

database/migrations/2023_02_28_122221_create_posts_table.php

<?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('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('body');
            $table->timestamps();
        });
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down(): void
    {
        Schema::dropIfExists('posts');
    }
};

To generate a new migration in Laravel, employ the subsequent command:

Also Read: How to Add Foreign Key in MIGRATION using Laravel?

php artisan migrate

The upcoming command will be employed to create the Post model:

php artisan make:model Post
app/Models/Post.php
<?php
  
namespace App\Models;
  
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
  
class Post extends Model
{
    use HasFactory;
    /**
     * Write code on Method
     *
     * @return response()
     */
    protected $fillable = [
        'title', 'body'
    ];
}

Step 3: Create Controller

In this crucial step, we will demonstrate how to craft a brand-new PostController, complete with the essential methods index() and store(). These methods are designed to efficiently render views and generate posts while also providing JSON responses.

To create your PostController swiftly, simply execute the following command:

Also Read: How to Rollback Migration in Laravel?

php artisan make:controller PostController

Let’s proceed to enhance the Controller File by incorporating the following code.

app/Http/Controllers/PostController.php
<?php
    
namespace App\Http\Controllers;
    
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Models\Post;
use Illuminate\View\View;
use Illuminate\Http\JsonResponse;
    
class PostController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(): View
    {
        $posts = Post::get();
    
        return view('posts', compact('posts'));
    }
    
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function store(Request $request): JsonResponse
    {
        $request->validate([
            'title' => 'required',
            'body' => 'required',
        ]);
         
        Post::create([
            'title' => $request->title,
            'body' => $request->body,
        ]);
    
        return response()->json(['success' => 'Post created successfully.']);
    }
}

Step 4: Create and Add Routes

Follow these steps:

  1. Begin by making adjustments to the “routes/web.php” file. Insert the necessary routes to manage both GET and POST requests for rendering views and handling AJAX POST requests.
routes/web.php

Also Read: How to Drop Soft Delete from Table using Migration in LARAVEL?

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\PostController;
  
/*
|--------------------------------------------------------------------------
| 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::controller(PostController::class)->group(function(){
    Route::get('posts', 'index');
    Route::post('posts', 'store')->name('posts.store');
});

Step 5: Create Blade File

The final step involves creating the “posts.blade.php” file, which plays a crucial role in showcasing all your posts and facilitating the implementation of jQuery AJAX request functionality. To complete this step, simply copy the provided code snippet below and paste it into the designated file.

resources/views/posts.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>Laravel 10 Ajax Form Validation Example - itcodestuff.com</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" ></script>
    <meta name="csrf-token" content="{{ csrf_token() }}" />
</head>
<body>
       
<div class="container">
    <div class="card bg-light mt-3">
        <div class="card-header">
            Laravel 10 Ajax Form Validation Example - itcodestuff.com
        </div>
        <div class="card-body">
    
            <table class="table table-bordered mt-3">
                <tr>
                    <th colspan="3">
                        List Of Posts
                        <button type="button" class="btn btn-success float-end" data-bs-toggle="modal" data-bs-target="#postModal">
                          Create Post
                        </button>
                    </th>
                </tr>
                <tr>
                    <th>ID</th>
                    <th>Title</th>
                    <th>Body</th>
                </tr>
                @foreach($posts as $post)
                <tr>
                    <td>{{ $post->id }}</td>
                    <td>{{ $post->title }}</td>
                    <td>{{ $post->body }}</td>
                </tr>
                @endforeach
            </table>
    
        </div>
    </div>
</div>
    
<!-- Modal -->
<div class="modal fade" id="postModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Create Post</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <form id="ajax-form" action="{{ route('posts.store') }}">
            @csrf
    
            <div class="alert alert-danger print-error-msg" style="display:none">
                <ul></ul>
            </div>
      
            <div class="mb-3">
                <label for="titleID" class="form-label">Title:</label>
                <input type="text" id="titleID" name="title" class="form-control" placeholder="Name">
            </div>
    
            <div class="mb-3">
                <label for="bodyID" class="form-label">Body:</label>
                <textarea name="body" class="form-control" id="bodyID"></textarea>
            </div>
       
            <div class="mb-3 text-center">
                <button class="btn btn-success btn-submit">Submit</button>
            </div>
      
        </form>
      </div>
    </div>
  </div>
</div>
       
</body>
    
<script type="text/javascript">
        
    /*------------------------------------------
    --------------------------------------------
    Form Submit Event
    --------------------------------------------
    --------------------------------------------*/
    $('#ajax-form').submit(function(e) {
        e.preventDefault();
       
        var url = $(this).attr("action");
        let formData = new FormData(this);
  
        $.ajax({
                type:'POST',
                url: url,
                data: formData,
                contentType: false,
                processData: false,
                success: (response) => {
                    alert('Form submitted successfully');
                    location.reload();
                },
                error: function(response){
                    $('#ajax-form').find(".print-error-msg").find("ul").html('');
                    $('#ajax-form').find(".print-error-msg").css('display','block');
                    $.each( response.responseJSON.errors, function( key, value ) {
                        $('#ajax-form').find(".print-error-msg").find("ul").append('<li>'+value+'</li>');
                    });
                }
           });
      
    });
    
</script>
    
</html>

Step 6: Run Laravel App:

Once you’ve successfully completed all the required steps, it’s time to enter the following command and hit Enter to initiate the Laravel application:

php artisan serve

To access the app’s output, simply input the supplied URL into your web browser.

Also Read: How To Send Email In Laravel 9

http://localhost:8000/posts

Your quest for the best Laravel blog ends here, where expert knowledge meets curated excellence.

Leave a Comment