Laravel form Submit Using Ajax with validation Example

laravel form submit using ajax

In this article, I will guide you Laravel form Submit Using Ajax with validation Example. I will show you step by step guide to store data using ajax. Here we are going to share how to submit data a click event using jquery ajax request and save data into database table.

In this article we will learn about the following things in order to do Larvel form submit using ajax -:

  • How to create controller using command
  • How to create migration and model together using command
  • Form validation using Jquery
  • Submitting the form using Jquery ajax post

Create Controller Using Command

Write the below code to create controller using commad, we will create a Contact controller using this command.

php artisan make:controller ContactController

After running this code a controller will create inside you app/http/controller folder.

Create Routes

Now we will create routes, one for showing our form and another for saving the data into our database.

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

Create Model and Migration Together

Now we will create model and migration together using the single command, run the below command to create model and migration together.

php artisan make:model Contact -m

This command will create model and migration together.

Now go to database\migrations\2021_07_26_073343_create_contacts_table.php and add the below code into 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')->nullable();
            $table->string('email')->nullable();
            $table->string('mobile_number')->nullable();
            $table->string('subject')->nullable();
            $table->text('message')->nullable();
            $table->timestamps();
        });
    }

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

Now go to app/http/models and open contact.php file and write the below code into it.I will use guarded as the fillable property to insert all data.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Contact extends Model
{
    /**
      * The attributes that are mass assignable.
      *
      * @var array
      */
     protected $guarded = [''];
}

Add code in your controller

Now go to app/Http/Controllers/ContactController.php and add the below code into it.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\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!']);

    }
}

Create blade file

Now we will create blade file under resources\views\ named as contact-form.blade.php and In the below code I will add code for contact form as well as I will write the code for validation and submit the form using ajax in laravel then write the below code into it.

<html lang="en">
<head>
    <title>CodeHunger 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>

Read Also: PHP Ajax Post Request Example

I hope you like the above article, give me a star if your problem is solved.

5 1 vote
Article Rating

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