In this tutorial, We will explain to you how to create Laravel 11 Ajax CRUD Example Tutorial. we give you information on the laravel 11 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 11 CRUD Operation With Ajax Example(laravel 11 ajax crud application). it was released on March 12, 2024.

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

Overview

Step 1: Install Laravel 11
Step 2: MySQL Database Configuration
Step 3: Create Migration Table
Step 4: Install Yajra Datatable
Step 5: Create Route
Step 6: Create Controller and Model
Step 7: Add Blade Files
Step 8: Run Laravel Application

Step 1 : Install Laravel 11

We are going to install laravel 11, 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 laravel/laravel:^11.0 laravel_11_ajax_crud

Step 2: MySQL 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=laravel_11_ajax_crud
DB_USERNAME=root
DB_PASSWORD=
DB_COLLATION=utf8mb4_unicode_ci

Step 3: Create Migration Table

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\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('students', function (Blueprint $table) {
            $table->id();
			$table->string('first_name');
            $table->string('last_name');
            $table->text('address');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('students');
    }
};
?>

Run the below command. after the changes above file.

php artisan migrate

Step 4: Install Yajra Datatable
In this step, we will intall yajra datatable using the below command.

composer require yajra/laravel-datatables

Step 5: Create Route

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

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\StudentController;
Route::get('/', function () {
    return view('welcome');
});
Route::resource('students', StudentController::class);
?>

Step 6: 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 DataTables;
use Illuminate\Http\JsonResponse;
class StudentController extends Controller
{
    /**
     * Display a listing of the resource.
	 * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        if ($request->ajax()) {
    
            $data = Student::query();
    
            return Datatables::of($data)
			->addIndexColumn()
			->addColumn('action', function($row){

				   $btn = '<a href="javascript:void(0)" data-toggle="tooltip"  data-id="'.$row->id.'" data-original-title="View" class="me-1 btn btn-info btn-sm showStudent"><i class="fa-regular fa-eye"></i> View</a>';
				   $btn = $btn. '<a href="javascript:void(0)" data-toggle="tooltip"  data-id="'.$row->id.'" data-original-title="Edit" class="edit btn btn-primary btn-sm editStudent"><i class="fa-regular fa-pen-to-square"></i> Edit</a>';

				   $btn = $btn.' <a href="javascript:void(0)" data-toggle="tooltip"  data-id="'.$row->id.'" data-original-title="Delete" class="btn btn-danger btn-sm deleteStudent"><i class="fa-solid fa-trash"></i> Delete</a>';

					return $btn;
			})
			->rawColumns(['action'])
			->make(true);
        }
          
        return view('students');
    }

    /**
     * Store a newly created resource in storage.
	 * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request): JsonResponse
    {
        $request->validate([
            'first_name' => 'required',
            'last_name' => 'required',
            'address' => 'required',
        ]);
          
        Student::updateOrCreate([
			'id' => $request->student_id
		],
		[
			'first_name' => $request->first_name, 
			'last_name' => $request->last_name, 
			'address' => $request->address
		]);        
       
        return response()->json(['success'=>'Student saved successfully.']);
    }

    /**
     * Display the specified resource.
	 * @param  \App\Student  $student
     * @return \Illuminate\Http\Response
     */
    public function show($id): JsonResponse
    {
        $student = Student::find($id);
        return response()->json($student);
    }

    /**
     * Show the form for editing the specified resource.
	 * @param  \App\Student  $student
     * @return \Illuminate\Http\Response
     */
    public function edit($id): JsonResponse
    {
        $student = Student::find($id);
        return response()->json($student);
    }

    /**
     * Remove the specified resource from storage.
	 * @param  \App\Student  $student
     * @return \Illuminate\Http\Response
     */
    public function destroy($id): JsonResponse
    {
        Student::find($id)->delete();
        return response()->json(['success'=>'Student deleted successfully.']);
    }
}
?>

Step 7: Add Blade Files

So finally, first we will new file of “students.blade.php” in the “resources/views/” directory.

resources/views/students.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 11 Ajax CRUD Example - xpertphp.com</title>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.1/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/1.11.4/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.5.1.js"></script>
    <script src="https://cdn.datatables.net/1.11.4/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.4/js/dataTables.bootstrap5.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" ></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" />
</head>
<body>
      
<div class="container">
    <div class="card mt-5">
        <h2 class="card-header"><i class="fa-regular fa-credit-card"></i> Laravel 11 Ajax CRUD Example - xpertphp.com</h2>
        <div class="card-body">
            <div class="d-grid gap-2 d-md-flex justify-content-md-end mb-3">
                <a class="btn btn-success btn-sm" href="javascript:void(0)" id="createNewStudent"> <i class="fa fa-plus"></i> Create New Student</a>
            </div>

            <table class="table table-bordered data-table">
                <thead>
                    <tr>
                        <th width="60px">No</th>
                        <th>First Name</th>
                        <th>Last Name</th>
                        <th>Address</th>
                        <th width="280px">Action</th>
                    </tr>
                </thead>
                <tbody>
                </tbody>
            </table>
        </div>
    </div>
    
</div>
     
<div class="modal fade" id="ajaxModel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="modelHeading"></h4>
            </div>
            <div class="modal-body">
                <form id="studentForm" name="studentForm" class="form-horizontal">
                   <input type="hidden" name="student_id" id="student_id">
                   @csrf

                    <div class="alert alert-danger print-error-msg" style="display:none">
                        <ul></ul>
                    </div>

                    <div class="form-group">
                        <label for="first_name" class="col-sm-3 control-label">First Name:</label>
                        <div class="col-sm-12">
                            <input type="text" class="form-control" id="first_name" name="first_name" placeholder="Enter First Name" value="" maxlength="50">
                        </div>
                    </div>
					
					<div class="form-group">
                        <label for="last_name" class="col-sm-3 control-label">Last Name:</label>
                        <div class="col-sm-12">
                            <input type="text" class="form-control" id="last_name" name="last_name" placeholder="Enter Last Name" value="" maxlength="50">
                        </div>
                    </div>
       
                    <div class="form-group">
                        <label class="col-sm-2 control-label">Address:</label>
                        <div class="col-sm-12">
                            <textarea id="address" name="address" placeholder="Enter Address" class="form-control"></textarea>
                        </div>
                    </div>
        
                    <div class="col-sm-offset-2 col-sm-10">
                     <button type="submit" class="btn btn-success mt-2" id="saveBtn" value="create"><i class="fa fa-save"></i> Submit
                     </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="showModel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="modelHeading"><i class="fa-regular fa-eye"></i> Show Student</h4>
            </div>
            <div class="modal-body">
                <p><strong>First Name:</strong> <span class="show-first-name"></span></p>
                <p><strong>Last Name:</strong> <span class="show-last-name"></span></p>
                <p><strong>Address:</strong> <span class="show-address"></span></p>
            </div>
        </div>
    </div>
</div>
      
</body>
      
<script type="text/javascript">
  $(function () {

    /*------------------------------------------
     --------------------------------------------
     Pass Header Token
     --------------------------------------------
     --------------------------------------------*/ 
    $.ajaxSetup({
          headers: {
              'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          }
    });
      
    /*------------------------------------------
    --------------------------------------------
    Render DataTable
    --------------------------------------------
    --------------------------------------------*/
    var table = $('.data-table').DataTable({
        processing: true,
        serverSide: true,
        ajax: "{{ route('students.index') }}",
        columns: [
            {data: 'DT_RowIndex', name: 'DT_RowIndex',searchable: false, orderable: false},
            {data: 'first_name', name: 'first_name'},
            {data: 'last_name', name: 'last_name'},
            {data: 'address', name: 'address'},
            {data: 'action', name: 'action', orderable: false, searchable: false},
        ]
    });
      
    /*------------------------------------------
    --------------------------------------------
    Click to Button
    --------------------------------------------
    --------------------------------------------*/
    $('#createNewStudent').click(function () {
        $('#saveBtn').val("create-student");
        $('#student_id').val('');
        $('#studentForm').trigger("reset");
        $('#modelHeading').html("<i class='fa fa-plus'></i> Create New Student");
        $('#ajaxModel').modal('show');
    });

    /*------------------------------------------
    --------------------------------------------
    Click to Edit Button
    --------------------------------------------
    --------------------------------------------*/
    $('body').on('click', '.showStudent', function () {
      var student_id = $(this).data('id');
      $.get("{{ route('students.index') }}" +'/' + student_id, function (data) {
          $('#showModel').modal('show');
          $('.show-first-name').text(data.first_name);
          $('.show-last-name').text(data.last_name);
          $('.show-address').text(data.address);
      })
    });
      
    /*------------------------------------------
    --------------------------------------------
    Click to Edit Button
    --------------------------------------------
    --------------------------------------------*/
    $('body').on('click', '.editStudent', function () {
      var student_id = $(this).data('id');
      $.get("{{ route('students.index') }}" +'/' + student_id +'/edit', function (data) {
          $('#modelHeading').html("<i class='fa-regular fa-pen-to-square'></i> Edit Student");
          $('#saveBtn').val("edit-user");
          $('#ajaxModel').modal('show');
          $('#student_id').val(data.id);
          $('#first_name').val(data.first_name);
          $('#last_name').val(data.last_name);
          $('#address').val(data.address);
      })
    });
      
    /*------------------------------------------
    --------------------------------------------
    Create student Code
    --------------------------------------------
    --------------------------------------------*/
    $('#studentForm').submit(function(e) {
        e.preventDefault();
 
        let formData = new FormData(this);
        $('#saveBtn').html('Sending...');
  
        $.ajax({
                type:'POST',
                url: "{{ route('students.store') }}",
                data: formData,
                contentType: false,
                processData: false,
                success: (response) => {
                      $('#saveBtn').html('Submit');
                      $('#studentForm').trigger("reset");
                      $('#ajaxModel').modal('hide');
                      table.draw();
                },
                error: function(response){
                    $('#saveBtn').html('Submit');
                    $('#studentForm').find(".print-error-msg").find("ul").html('');
                    $('#studentForm').find(".print-error-msg").css('display','block');
                    $.each( response.responseJSON.errors, function( key, value ) {
                        $('#studentForm').find(".print-error-msg").find("ul").append('<li>'+value+'</li>');
                    });
                }
           });
      
    });
      
    /*------------------------------------------
    --------------------------------------------
    Delete Student Code
    --------------------------------------------
    --------------------------------------------*/
    $('body').on('click', '.deleteStudent', function () {
     
        var student_id = $(this).data("id");
        confirm("Are You sure want to delete?");
        
        $.ajax({
            type: "DELETE",
            url: "{{ route('students.store') }}"+'/'+student_id,
            success: function (data) {
                table.draw();
            },
            error: function (data) {
                console.log('Error:', data);
            }
        });
    });
       
  });
</script>
</html>

Step 8: Run 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/students

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

Download code from github