Laravel Insert Record using jQuery Ajax

In this post we have learn Laravel Insert Record using jQuery Ajax. Also we have learn ajax country state city dropdown demo, jquery plugin for country state city dropdown, jquery form validation, form validation using ajax and jquery in laravel ect.

Laravel Insert Record using jQuery Ajax

routes/web.php

<?php

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

Route::get("/", [DemoController::class,'index']);
Route::get('get-states-by-country',[DemoController::class,'getState']);
Route::post('get-cities-by-state',[DemoController::class,'getCity']);

Route::post("store",[DemoController::class,"store"]);

Create DemoController.php controller file.

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\{Country,State,City,Demo};
use Validator;
use DB;

  class DemoController extends Controller
  {
    function index(){
    $data['countries'] =DB::table('countries')->get(["name","id"]);
    return view('form',$data);
  }

  public function getState(Request $request)
  {
    $data['states'] = DB::table('states')->where("country_id",$request->country_id)
    ->get(["name","id"]);
    return response()->json($data);
  }

  public function getCity(Request $request)
 {
   $data['cities'] = DB::table('cities')->where("state_id",$request->state_id)
   ->get(["name","id"]);
   return response()->json($data);
 }

 public function store(Request $request){

  $img = time()."_".$request->file->getClientOriginalName();
  $validator = Validator::make($request->all(), [
    'name' => 'required',
    'email' => 'required',
    'gender' => 'required',
    'country' => 'required',
    'state' => 'required',
    'city' => 'required',
    'file' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);


if ($validator->passes()) {
  $demo = new Demo;
  $demo->name = $request->name;
  $demo->email = $request->email;
  $demo->gender = $request->gender;
  $demo->country = $request->country;
  $demo->state = $request->state;
  $demo->city = $request->city;
  $demo->file = $img;
  if($demo->save()){
  $request->file->move(public_path('images'),$img);
   return response()->json(['success'=>'Added new records.']);
 }
}else{
  return response()->json($validator->errors()->all());
  }
 }
}

Create Demo.php model file.

<?php

namespace App;
use Illuminate\Database\Eloquent\Model;

class Demo extends Model
{
  protected $table = 'demo';
  public $timestamps = false;
}

Create form.blade.php view file.

<!DOCTYPE html>
<html lang="en">
 <head>
  <title>Laravel Insert using jquery ajax</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
 </head>
 <body>

  <div class="container">
   <h2>Form</h2>
   <form action="store" method="post" id="form" enctype="multipart/form-data" >
   @csrf

    <div class="form-group">
     <label for="name">Name:</label>
     <input type="text" class="form-control" id="name" placeholder="Enter name" name="name">
    </div>

    <div class="form-group">
     <label for="email">Email:</label>
     <input type="email" class="form-control" id="email" placeholder="Enter email" name="email">
    </div>

    <div class="form-group">
     <label for="gender">Gender:</label>
     <input type="radio" id="gender" name="gender" value="Male">Male
     <input type="radio" id="gender" name="gender" value="Female">Female
    </div>

    <div class="form-group">
     <label for="country">Country:</label>
     <select class="form-control" name="country" id="country" name="country">
      <option>Select</option>
       @foreach ($countries as $country) 
      <option value="{{$country->id}}">
       {{$country->name}}
      </option>
       @endforeach
     </select>
    </div>

    <div class="form-group">
     <label for="state">State:</label>
     <select class="form-control" name="state" id="state" name="state">
      <option>Select</option>
     </select>
    </div>

    <div class="form-group">
     <label for="city">City:</label>
     <select class="form-control" name="city" id="city" name="city">
      <option>Select</option>
     </select>
   </div>

   <div class="form-group">
    <label for="file">File:</label>
    <input type="file" name="file" placeholder="Choose File" id="file">
   </div>

  <button type="submit" class="btn btn-default">Submit</button>
 </form>
 </div>
<script>
 $(document).ready(function () {
  $('#country').change(function(){
   var countryID = $(this).val(); 
   if(countryID){
   $.ajax({
     type:"GET",
     url:"{{url('get-states-by-country')}}?country_id="+countryID,
     success:function(res){ 
      if(res){
        $("#state").empty();
        $("#state").append('<option>Select</option>');
        $("#city").empty();
        $("#city").append('<option>Select</option>');
        $.each(res.states,function(key,value){
         $("#state").append('<option value="'+value.id+'">'+value.name+'</option>');
       });
     }else{
   $("#state").empty();
  }
}
});
}else{
  $("#state").empty();
  $("#city").empty();
} 
});

$('#state').change(function(){
   var stateID = $(this).val(); 
   if(stateID){
    $.ajax({
     type:"POST",
     url:"{{url('get-cities-by-state')}}",
     data:{
       state_id : stateID,
       _token: '{{csrf_token()}}'
     },
     success:function(res){ 
     if(res){
       $("#city").empty();
       $("#city").append('<option>Select</option>');
       $.each(res.cities,function(key,value){
         $("#city").append('<option value="'+value.id+'">'+value.name+'</option>');
       });
     }else{
     $("#city").empty();
    }
  }
 });
}else{
  $("#city").empty();
} 
});

$("button").click(function (event) {
  event.preventDefault();

  var data = new FormData(form);

  $.ajax({
    type: "POST",
    url: "store",
    data: data,
    processData: false,
    contentType: false,
    success: function (data) {
    console.log(data);
    $('#form')[0].reset();
  },
  error: function(message, error) 
  {
   var er = message.responseJSON.errors;

   if(er.name){
   alert(er.name);
  }
 }
});
});
});
</script>
</body>
</html>

SQL file

--
-- Database: `laravel`
--

-- --------------------------------------------------------

--
-- Table structure for table `cities`
--

CREATE TABLE `cities` (
`id` int(10) UNSIGNED NOT NULL,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`state_id` int(11) NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `cities`
--

INSERT INTO `cities` (`id`, `name`, `state_id`, `created_at`, `updated_at`) VALUES
(1, 'Surat', 1, NULL, NULL),
(2, 'Rajkot', 1, NULL, NULL),
(3, 'Tughlakabad', 2, NULL, NULL),
(4, 'Shergarh', 2, NULL, NULL),
(5, 'Turbat', 3, NULL, NULL),
(6, 'Khuzdar', 3, NULL, NULL),
(7, 'Karachi\r\n', 4, NULL, NULL),
(8, 'Sukkur', 4, NULL, NULL);

-- --------------------------------------------------------

--
-- Table structure for table `countries`
--

CREATE TABLE `countries` (
`id` int(10) UNSIGNED NOT NULL,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `countries`
--

INSERT INTO `countries` (`id`, `name`, `created_at`, `updated_at`) VALUES
(1, 'India', NULL, NULL),
(2, 'Pakistan', NULL, NULL);

-- --------------------------------------------------------

--
-- Table structure for table `demo`
--

CREATE TABLE `demo` (
`id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`gender` varchar(255) NOT NULL,
`country` varchar(255) NOT NULL,
`state` varchar(255) NOT NULL,
`city` varchar(255) NOT NULL,
`file` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- --------------------------------------------------------

--
-- Table structure for table `states`
--

CREATE TABLE `states` (
`id` int(10) UNSIGNED NOT NULL,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`country_id` int(11) NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `states`
--

INSERT INTO `states` (`id`, `name`, `country_id`, `created_at`, `updated_at`) VALUES
(1, 'Gujarat', 1, NULL, NULL),
(2, 'Delhi', 1, NULL, NULL),
(3, 'Balochistan', 2, NULL, NULL),
(4, 'Sindh', 2, NULL, NULL);

--
-- Indexes for dumped tables
--

--
-- Indexes for table `cities`
--
ALTER TABLE `cities`
ADD PRIMARY KEY (`id`);

--
-- Indexes for table `countries`
--
ALTER TABLE `countries`
ADD PRIMARY KEY (`id`);

--
-- Indexes for table `demo`
--
ALTER TABLE `demo`
ADD PRIMARY KEY (`id`);

--
-- Indexes for table `states`
--
ALTER TABLE `states`
ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `cities`
--
ALTER TABLE `cities`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9;

--
-- AUTO_INCREMENT for table `countries`
--
ALTER TABLE `countries`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;

--
-- AUTO_INCREMENT for table `demo`
--
ALTER TABLE `demo`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `states`
--
ALTER TABLE `states`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;