In this tutorial, We will explain to you how to create Laravel 10 Ajax CRUD Example Tutorial. we give you information on the laravel 10 Ajax CRUD Example Tutorial from scratch for beginners.

Laravel is the most popular framework of PHP. laravel is better than other PHP frameworks because it handles the command base. so let us see about Laravel 10 CRUD Operation With Ajax Example(laravel 10 ajax crud application). it was released on February 7th, 2023.

Now, we follow the below step for creating the laravel 10 crud operation with ajax example.

Overview

Step 1: Install Laravel 10

Step 2: Setting Database Configuration

Step 3: Create Table using migration

Step 4: Create Resource Route in web.php file

Step 5: Create Model and Controller

Step 6: Create Blade Files

Step 7: Run Our Laravel Application

Step 1 : Install Laravel 10

We are going to install laravel 10, so first open the command prompt or terminal and go to xampp htdocs folder directory using the command prompt. after then run the below command.

composer create-project --prefer-dist laravel/laravel:^10.0 laravel10_ajax_crud

Step 2: Setting Database Configuration

After complete installation of laravel. we have to database configuration. now we will open the .env file and change the database name, username, password in the .env file. See below changes in a .env file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=Enter_Your_Database_Name(laravel10_ajax_crud)
DB_USERNAME=Enter_Your_Database_Username(root)
DB_PASSWORD=Enter_Your_Database_Password(root)

Step 3: Create Table using migration

Now, We need to create a migration. so we will below command using create the students table migration.

php artisan make:migration create_students_table --create=students

After complete migration. we need below changes in the database/migrations/create_students_table file.

<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateStudentsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('students', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('first_name');
            $table->string('last_name');
            $table->text('address');
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('students');
    }
}
?>

Run the below command. after the changes above file.

php artisan migrate

Step 4: Create a Custom Route in web.php file

We have to need put below route in routes/web.php file.

<?php
use App\Http\Controllers\StudentController;
/*
|--------------------------------------------------------------------------
| 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::get('/', function () {
   // return view('welcome');	
});
Route::get('student','App\Http\Controllers\StudentController@index');
Route::post('student','App\Http\Controllers\StudentController@store')->name('student.store');
Route::get('student/{id}/edit', 'App\Http\Controllers\StudentController@edit')->name('student.edit');
Route::post('student/update', 'App\Http\Controllers\StudentController@update')->name('student.update');
Route::get('student/{id}/delete', 'App\Http\Controllers\StudentController@destroy')->name('student.delete');

?>

Step 5: Create Model and Controller

Here below command help to create the controller and model.

php artisan make:controller StudentController --resource --model=Student

Student.php

<?php

namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Student extends Model
{
    use HasFactory;
    protected $fillable = [
        'first_name','last_name', 'address'
    ];
}
?>

StudentController.php

<?php

namespace App\Http\Controllers;

use App\Models\Student;
use Illuminate\Http\Request;
use Response;
class StudentController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
		$data['students'] = Student::orderBy('id','desc')->paginate(5);   
        return view('student.list',$data);
    }
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {		
		$student = new Student([
            'first_name' => $request->post('txtFirstName'),
            'last_name'=> $request->post('txtLastName'),
            'address'=> $request->post('txtAddress')
        ]);
		$student->save();    
        return Response::json($student);
    }
    /**
     * Display the specified resource.
     *
     * @param  \App\Student  $student
     * @return \Illuminate\Http\Response
     */
    public function show(Student $student)
    {
        //
    }
    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Student  $student
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
		$where = array('id' => $id);
        $student  = Student::where($where)->first();
 
        return Response::json($student);
    }
    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Student  $student
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request)
    {
        //
		$student = Student::find($request->post('hdnStudentId'));
        $student->first_name = $request->post('txtFirstName');
        $student->last_name = $request->post('txtLastName');
        $student->address = $request->post('txtAddress');
        $student->update();
		return Response::json($student);
		
    }
    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Student  $student
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
        $student = Student::where('id',$id)->delete();
        return Response::json($student);
    }
}
?>

Step 6: Create Blade Files

So finally, first we will create the new directory “resources/views/layouts” and that directory in create a “resources/views/layouts/app.blade.php” file. and the second time we will create a list.blade.php in the “resources/ views/student/” directory.

app.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Laravel 10 Ajax CRUD Example</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.0/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>
</head>
<body>
<div class="container">
    @yield('content')
</div>
</body>
</html>

list.blade.php

@extends('layouts.app')
@section('content')
    <div class="row">
        <div class="col-lg-11">
                <h2>Laravel 10 Ajax CRUD Example</h2>
        </div>
        <div class="col-lg-1">
            <a class="btn btn-success" href="#" data-toggle="modal" data-target="#addModal">Add</a>
        </div>
    </div>
    @if ($message = Session::get('success'))
        <div class="alert alert-success">
            <p>{{ $message }}</p>
        </div>
    @endif
    <table class="table table-bordered" id="studentTable">
		<thead>
			<tr>
				<th>id</th>
				<th>First Name</th>
				<th>Last Name</th>
				<th>Address</th>
				<th width="280px">Action</th>
			</tr>
		</thead>	
		<tbody>
        @foreach ($students as $student)
            <tr id="{{ $student->id }}">
                <td>{{ $student->id }}</td>
                <td>{{ $student->first_name }}</td>
                <td>{{ $student->last_name }}</td>
                <td>{{ $student->address }}</td>
                <td>
		     <a data-id="{{ $student->id }}" class="btn btn-primary btnEdit">Edit</a>
		     <a data-id="{{ $student->id }}" class="btn btn-danger btnDelete">Delete</button>
                </td>
            </tr>
        @endforeach
		</tbody>
    </table>
	

<!-- Add Student Modal -->
<div id="addModal" class="modal fade" role="dialog">
  <div class="modal-dialog">

    <!-- Student Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Add New Student</h4>
      </div>
	  <div class="modal-body">
		<form id="addStudent" name="addStudent" action="{{ route('student.store') }}" method="post">
			@csrf
			<div class="form-group">
				<label for="txtFirstName">First Name:</label>
				<input type="text" class="form-control" id="txtFirstName" placeholder="Enter First Name" name="txtFirstName">
			</div>
			<div class="form-group">
				<label for="txtLastName">Last Name:</label>
				<input type="text" class="form-control" id="txtLastName" placeholder="Enter Last Name" name="txtLastName">
			</div>
			<div class="form-group">
				<label for="txtAddress">Address:</label>
				<textarea class="form-control" id="txtAddress" name="txtAddress" rows="10" placeholder="Enter Address"></textarea>
			</div>
			<button type="submit" class="btn btn-primary">Submit</button>
		</form>
	  </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>	
<!-- Update Student Modal -->
<div id="updateModal" class="modal fade" role="dialog">
  <div class="modal-dialog">

    <!-- Student Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Update Student</h4>
      </div>
	  <div class="modal-body">
		<form id="updateStudent" name="updateStudent" action="{{ route('student.update') }}" method="post">
			<input type="hidden" name="hdnStudentId" id="hdnStudentId"/>
			@csrf
			<div class="form-group">
				<label for="txtFirstName">First Name:</label>
				<input type="text" class="form-control" id="txtFirstName" placeholder="Enter First Name" name="txtFirstName">
			</div>
			<div class="form-group">
				<label for="txtLastName">Last Name:</label>
				<input type="text" class="form-control" id="txtLastName" placeholder="Enter Last Name" name="txtLastName">
			</div>
			<div class="form-group">
				<label for="txtAddress">Address:</label>
				<textarea class="form-control" id="txtAddress" name="txtAddress" rows="10" placeholder="Enter Address"></textarea>
			</div>
			<button type="submit" class="btn btn-primary">Submit</button>
		</form>
	  </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>	

<script>
  $(document).ready(function () {
	//Add the Student  
	$("#addStudent").validate({
		 rules: {
				txtFirstName: "required",
				txtLastName: "required",
				txtAddress: "required"
			},
			messages: {
			},
 
		 submitHandler: function(form) {
		  var form_action = $("#addStudent").attr("action");
		  $.ajax({
			  data: $('#addStudent').serialize(),
			  url: form_action,
			  type: "POST",
			  dataType: 'json',
			  success: function (data) {
				  var student = '<tr id="'+data.id+'">';
				  student += '<td>' + data.id + '</td>';
				  student += '<td>' + data.first_name + '</td>';
				  student += '<td>' + data.last_name + '</td>';
				  student += '<td>' + data.address + '</td>';
				  student += '<td><a data-id="' + data.id + '" class="btn btn-primary btnEdit">Edit</a>&nbsp;&nbsp;<a data-id="' + data.id + '" class="btn btn-danger btnDelete">Delete</a></td>';
				  student += '</tr>';            
				  $('#studentTable tbody').prepend(student);
				  $('#addStudent')[0].reset();
				  $('#addModal').modal('hide');
			  },
			  error: function (data) {
			  }
		  });
		}
	});
  
 
    //When click edit student
    $('body').on('click', '.btnEdit', function () {
      var student_id = $(this).attr('data-id');
      $.get('student/' + student_id +'/edit', function (data) {
          $('#updateModal').modal('show');
          $('#updateStudent #hdnStudentId').val(data.id); 
          $('#updateStudent #txtFirstName').val(data.first_name);
          $('#updateStudent #txtLastName').val(data.last_name);
          $('#updateStudent #txtAddress').val(data.address);
      })
   });
    // Update the student
	$("#updateStudent").validate({
		 rules: {
				txtFirstName: "required",
				txtLastName: "required",
				txtAddress: "required"
				
			},
			messages: {
			},
 
		 submitHandler: function(form) {
		  var form_action = $("#updateStudent").attr("action");
		  $.ajax({
			  data: $('#updateStudent').serialize(),
			  url: form_action,
			  type: "POST",
			  dataType: 'json',
			  success: function (data) {
				  var student = '<td>' + data.id + '</td>';
				  student += '<td>' + data.first_name + '</td>';
				  student += '<td>' + data.last_name + '</td>';
				  student += '<td>' + data.address + '</td>';
				  student += '<td><a data-id="' + data.id + '" class="btn btn-primary btnEdit">Edit</a>&nbsp;&nbsp;<a data-id="' + data.id + '" class="btn btn-danger btnDelete">Delete</a></td>';
				  $('#studentTable tbody #'+ data.id).html(student);
				  $('#updateStudent')[0].reset();
				  $('#updateModal').modal('hide');
			  },
			  error: function (data) {
			  }
		  });
		}
	});		
		
   //delete student
	$('body').on('click', '.btnDelete', function () {
      var student_id = $(this).attr('data-id');
      $.get('student/' + student_id +'/delete', function (data) {
          $('#studentTable tbody #'+ student_id).remove();
      })
   });	
	
});	  
</script>
@endsection

Step 7: Run Our Laravel Application
We can start the server and run this example using the below command.

php artisan serve

Now we will run our example using the below Url in the browser.

http://127.0.0.1:8000/student

if you want to download source code then you can visit below link url for source code example github.

github