Laravel 9 – Form Submit using Ajax with Validation

Laravel 9 Form Submit using Ajax Example; In this tutorial you will learn how to Submit Form using Ajax in Laravel 9 with Validations Example step by step from scratch.

To saving data in database using laravel 9 we use POST request to submit data using ajax jquery easy step. Using jquery ajax request we submit data in database without refresh the page also show the error and success messages easily. So lets go..

Step 1: Add Routes

First at all open the routes/web.php file and add two routes on it.

<?php

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

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


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

Step 2: Create Model & Migration File

Next, Run the below command to generate new model and migration file.

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 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_number');
            $table->string('subject');
            $table->text('message');
            $table->timestamps();
        });
    }

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

Run the follow command for generating database tables.

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_number', 'subject', 'message'
    ];
}

Step 3: Create Controller

Create a new controller just run the below 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('contact-form');
    }

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

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

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

  }
}

Step 4: Create Blade File

Crate a new blade file named as contact-form.blade.php, which is show the form where we send the ajax request for showing form validations and etc functionalities. So, open the resources\views\contact-form.blade.php file and upate the below cod on it

<html lang="en">
<head>
    <title>Laravel Ajax jquery Validation Tutorial</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
</head>
<body>

<div class="container panel panel-default ">
        <h2 class="panel-heading">Laravel Ajax jquery Validation</h2>
    <form id="contact-form">
        <div class="form-group">
            <input type="text" name="name" class="form-control" placeholder="Enter Name" id="name">
            <span class="text-danger" id="name-error"></span>
        </div>

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

        <div class="form-group">
            <input type="text" name="mobile_number" class="form-control" placeholder="Enter Mobile Number" id="mobile_number">
            <span class="text-danger" id="mobile-number-error"></span>
        </div>

        <div class="form-group">
            <input type="text" name="subject" class="form-control" placeholder="Enter subject" id="subject">
            <span class="text-danger" id="subject-error"></span>
        </div>

        <div class="form-group">
          <textarea class="form-control" name="message" placeholder="Message" id="message"></textarea>
          <span class="text-danger" id="message-error"></span>
        </div>
        <div class="form-group">
            <button class="btn btn-success" id="submit">Submit</button>
        </div>
        <div class="form-group">
            <b><span class="text-success" id="success-message"> </span><b>
        </div>
    </form>
</div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>

   <script type="text/javascript">
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

    $('#contact-form').on('submit', function(event){
        event.preventDefault();
        $('#name-error').text('');
        $('#email-error').text('');
        $('#mobile-number-error').text('');
        $('#subject-error').text('');
        $('#message-error').text('');

        name = $('#name').val();
        email = $('#email').val();
        mobile_number = $('#mobile_number').val();
        subject = $('#subject').val();
        message = $('#message').val();

        $.ajax({
          url: "/contact-form",
          type: "POST",
          data:{
              name:name,
              email:email,
              mobile_number:mobile_number,
              subject:subject,
              message:message,
          },
          success:function(response){
            console.log(response);
            if (response) {
              $('#success-message').text(response.success);
              $("#contact-form")[0].reset();
            }
          },
          error: function(response) {
              $('#name-error').text(response.responseJSON.errors.name);
              $('#email-error').text(response.responseJSON.errors.email);
              $('#mobile-number-error').text(response.responseJSON.errors.mobile_number);
              $('#subject-error').text(response.responseJSON.errors.subject);
              $('#message-error').text(response.responseJSON.errors.message);
          }
         });
        });
      </script>
 </body>
</html>

Great! you have learned Laravel 8 Form Submit Using Ajax with Validations Example tutorials. I hope this is work for you.. If any question feel free to contact below.

1 thought on “Laravel 9 – Form Submit using Ajax with Validation”

Leave a Comment