CodeIgniter Laravel PHP Example HTML Javascript jQuery MORE Videos New

How to Laravel 8 Insert data using Ajax


Step 1 web.php

web.php

Route::get('/insert','StudInsertController@index')->name('student form');
Route::post('/create','StudInsertController@store')->name('student form create');

Step 2 : EmployeeController.php

EmployeeController.php

<?php

namespace App\Http\Controllers;

use App\Models\Employee;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use \Illuminate\Http\Response;
class EmployeeController extends Controller
{
    
	public function __construct()
    {
        /* $this->middleware('auth'); */
    }
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('employee.add');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
		$status = 0;
		$rules = [
			'first_name' => 'required|string|min:3|max:255',
			'city_name' => 'required|string|min:3|max:255',
			'email' => 'required|string|email|max:255|unique:employees'
		];
		$validator = Validator::make($request->all(),$rules);
		if ($validator->fails()) {
			$contents = array("message"=>$validator->errors());
			$status=400;
		}
		else{
			$data = $request->input();
			if ($status!=400){
				$employee = new Employee;
				$employee->first_name = $data['first_name'];
				$employee->last_name = $data['last_name'];
				$employee->city_name = $data['city_name'];
				$employee->email = $data['email'];
				try{
					$employee->save();
					$contents = array(
						"message"=>"data save successfully",
						"id"=>$employee->id
					);
					$status=200;
				}
				catch(Exception $e){
					$contents = array("message"=>"Internal Server Error");
					$status=500;
				}

			}
			else{
				$contents = array("message"=>"Something went wrong");
				$status=500;
			}
		}
		$response = response($contents, $status);
		return $response;
    }

}

Step 3 Employee.php (model)

Employee.php (model)

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Employee extends Model
{
	// protected $table = 'employees';
	public $timestamps = true;
	protected $fillable = [
		'first_name', 'last_name','city_name', 'email',
	];
}

Step 4 layouts/app.blade.php(views): This is common file

app.blade.php

<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">

	<!-- CSRF Token -->
	<meta name="csrf-token" content="{{ csrf_token() }}">

	<title>{{ config('app.name', 'ST Laravel') }}</title>

	<!-- Scripts -->
	
	{{-- <script src="{{ asset('js/app.js') }}" defer></script> --}}

	<!-- Fonts -->
	<link rel="dns-prefetch" href="//fonts.gstatic.com">
	<link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet">
	<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
	<link rel="stylesheet" href="https://cdn.datatables.net/1.10.20/css/dataTables.bootstrap4.min.css">

	<!-- Styles -->
	{{-- <link href="{{ asset('css/app.css') }}" rel="stylesheet"> --}}
	<link href="{{ asset('css/bootstrap/bootstrap.min.css') }}" rel="stylesheet">
	<link href="{{ asset('css/select2/select2.min.css') }}" rel="stylesheet">
	<link href="{{ asset('css/main.css')}}" rel="stylesheet">
	
	<script type="text/javascript" src="{{ asset('js/jquery/jquery.min.js') }}"></script>
	<script src="{{ asset('js/bootstrap/popper.min.js') }}"></script>
	<script src="{{ asset('js/bootstrap/bootstrap.min.js') }}"></script>
	<script src="{{ asset('js/select2/select2.min.js') }}"></script>
	<script src="{{ asset('js/common.js') }}"></script>
	<script type="text/javascript" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
	<script type="text/javascript" src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap4.min.js"></script>
	
</head>
<body>
	<div id="app">
		<div class="main">
			@yield('content')
		</div>
	</div>		
</body>
</html>

employee/add.blade.php (views)

employee/add.blade.php (views)

@extends('layouts.app')

@section('content')
<div class="container">
	<h1 class="page-title">Employee Add</h1>
	<div class="" style="margin-bottom:10px;margin-top:15px;">
		
	</div>
	
	<div class="row justify-content-center">
		<div class="col-md-12">
			<div class="card">
				
				<div class="card-header">Add</div>
				<div class="card-body">
					<input type="hidden" name="_token" id="csrf" value="{{Session::token()}}">
					
					<div class="form-group">
						<label for="first_name">First Name:</label>
						<input type="text" name="first_name" id="first_name" class="form-control col-sm-6" placeholder="First Name" required />
						<div id="first_name-error" class="invalid-feedback"></div>
					</div>
					<div class="form-group">
						<label for="last_name">Last Name:</label>
						<input type="text" name="last_name" id="last_name" class="form-control col-sm-6" placeholder="Last Name" required />
						<div id="last_name-error" class="invalid-feedback"></div>
					</div>
					<div class="form-group">
						<label for="email">Email Id:</label>
						<input type="text" name="email" id="email" class="form-control col-sm-6" placeholder="Email Id" required />
						<div id="email-error" class="invalid-feedback"></div>
					</div>
					<div class="form-group">
						<label for="city_name">City Name:</label>
						<select class="form-control col-sm-6" id="city_name" name="city_name">
							<option value="delhi">Delhi</option>
							<option value="mumbai">Mumbai</option>
							<option value="chennai">Chennai</option>
							<option value="kolkata">Kolkata</option>
						</select>
						<div id="city_name-error" class="invalid-feedback"></div>
					</div>
					<div class="invalid-feedback backend-error" id="backend-error"></div>
					<div class="button-section" style="margin-top:15px;">
						
						<button type="button" id="save" class="btn btn-primary">Save</button>
					</div>
				</div>
			</div>
		</div>
	</div>
</div>
<script>
	$(document).ready(function(){
		$(document).on('click','#save',function(){
			var token = $(`#csrf`).val();
			var first_name = $("#first_name").val();
			var last_name = $("#last_name").val();
			var email = $("#email").val();
			var city_name = $("#city_name").val();
			
			if(first_name == "" || first_name == undefined || first_name == null){
				$(`#first_name`).addClass('is-invalid');
				$(`#first_name-error`).text('please enter first name');
				$(`#first_name`).focus();
			}
			else if(email==0|| email == undefined || email ==null || email == ""){
				$("#email").addClass('is-invalid');
				$("#email-error").text('please enter email id');
				$("#email").focus();
			}
			else if(city_name == "" || city_name == undefined || city_name == null || city_name == ""){
				alert("Please select city name");
			}
			else
			{
				var data = {
					"_token":token,
					"first_name":first_name,
					"last_name":last_name,
					"email":email,
					"city_name":city_name
				}
				var ajaxData = fetchData(
					"{{ url('employee/add') }}",
					"POST",
					data
				)
				$.when(ajaxData).then(function(result){
					// suceess
					window.location = `{{ url('/employee')}}`
					// alert("Data insert successfully");
					
				}).catch(function(jqXHR, exception){
					msg = catch_function(jqXHR, exception)
					mymsg="";
					mymsg_flag=true
					try{
						actualMsg = JSON.parse(msg)
						actualMsg = actualMsg['message']
						for(let key in actualMsg){
							if($(`#${key}`).length){
								$(`#${key}`).addClass('is-invalid');
								$(`#${key}-error`).text(actualMsg[key][0])
							}
							else{
								mymsg += actualMsg[key][0]
							}
						}
					}
					catch(err){
						mymsg = msg
						$(`.backend-error`).text(mymsg);
						$(`.backend-error`).show()
						mymsg_flag=false
					}
					if(mymsg.length && mymsg_flag){
						$(`.backend-error`).text(mymsg);
						$(`.backend-error`).show()
					}
				});
			}

			
		})
		$(document).on('change','.form-control',function(){
			$(this).removeClass('is-invalid');
		})
	})
</script>
@endsection

Step 5 table schema

use php artisan make:migration create_employees_table --create=employees to create migration file and 
paste the below code inside up() method
Schema::create('employees', function (Blueprint $table) {
	$table->id();
	$table->string('first_name');
	$table->string('last_name')->nullable();
	$table->string('city_name')->nullable();
	$table->string('email')->unique();
	$table->timestamps();
});

Now run the php artisan migrate command to create table in database.