Home Laravel 9 AJAX CRUD Application in Laravel 11

AJAX CRUD Application in Laravel 11

22 min read
0
0
1,679

Introduction to AJAX and Laravel 11

AJAX, which stands for Asynchronous JavaScript and XML which use to prevent of refresh the web pages.it allow us the user to create web application projects easy and fastest  way to implement of without refresh the page.

Laravel is a word best PHP framework to create the web application project.easy implement the all the function.in this tutoril will teach you to work with laravel with ajax.

Implementing CRUD Operations with AJAX in Laravel 11

first need to set up a new Laravel project  by running the following command to create a new project:

composer create-project --prefer-dist laravel/laravel ajax-crud

Once the project is created, set up your database configuration in the .env file. Provide the necessary details such as the database name, username, and password:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravelajax
DB_USERNAME=root
DB_PASSWORD=

Next step create the migrations and models for the CRUD operations.i am using the entity as Employee

php artisan make:model Employee -m

After that you can check the inside  database folder migrations  create_employees_table file has been created
successfully.

Select and open the employees table. add the following table fields.

public function up(): void
   {
       Schema::create('employees', function (Blueprint $table) {
           $table->id();
           $table->string('name');
           $table->string('email');
           $table->string('address'); 
           $table->string('phone');
           $table->timestamps();
          
       });
   }

After modified the columns names  then run the migrate command to create the tables in the databases.before the run the
command please save project then run it.

php artisan migrate

Configure Model

class Employee extends Model
{

    protected $table = 'employees';
    protected $primaryKey = 'id';
     protected $fillable = [
          'name',
          'email',
          'address',
          'phone',
      ];
      use HasFactory;
    use HasFactory;

}

Create Controller

Create the controller name which is EmployeeController 

php artisan make:controller EmployeeController

After created the controller paste this following code snippet

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Employee;

class EmployeeController extends Controller
{
    public function store(Request $request)
    {
        $empData = [
            'name' => $request->name,
            'email' => $request->email,
            'address' => $request->address,
            'phone' => $request->phone
        ];
        Employee::create($empData);
        return response()->json([
            'status' => 200,
        ]);
    }


    public function getall()
    {
        $employees = Employee::all();
        return response()->json([
            'status' => 200,
            'employees' => $employees
        ]);
    }

    public function edit($id)
    {
        $employee = Employee::find($id);
        if ($employee) {
            return response()->json([
                'status' => 200,
                'employee' => $employee
            ]);
        } else {
            return response()->json([
                'status' => 404,
                'message' => 'Employee not found'
            ]);
        }
    }

    public function update(Request $request)
    {
        $employee = Employee::find($request->id);
        if ($employee) {
            $employee->name = $request->name;
            $employee->email = $request->email;
            $employee->address = $request->address;
            $employee->phone = $request->phone;
            $employee->save();

            return response()->json([
                'status' => 200,
                'message' => 'Employee updated successfully'
            ]);
        } else {
            return response()->json([
                'status' => 404,
                'message' => 'Employee not found'
            ]);
        }
    }

    public function delete(Request $request)
{
    $employee = Employee::find($request->id);
    if ($employee && $employee->delete()) {
        return response()->json(['status' => 200, 'message' => 'Employee deleted successfully.']);
    } else {
        return response()->json(['status' => 400, 'message' => 'Failed to delete employee.']);
    }
}
}

Once the database is configured, proceed to build the frontend using HTML and JavaScript. Use jQuery to simplify the AJAX requests. Below is a sample HTML form for creating and updating and delete  Employees:

Implement similar AJAX requests for reading, updating, and deleting products.

By following these steps, you will create a robust and user-friendly application where CRUD operations are seamlessly integrated with AJAX, enhancing the user experience by updating the UI without full page reloads.

Create the Page Inside the resources folder which name is home.blade.php inside the page you have to paste the following code snippt.

home.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdn.datatables.net/2.1.2/css/dataTables.dataTables.css" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
</head>
<body>

    <div class="container">
        <div class="row">
            <div class="col-md-12">
                <div class="card mt-4 shadow">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h4>Employee Registation</h4>
                        <button type="button" class="btn btn-light" data-bs-toggle="modal" data-bs-target="#exampleModal">
                            <i class="bi bi-database-add"></i> ADD
                        </button>
                    </div>
                    <div class="card-body">
                        <table id="myTable" class="display">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>Name</th>
                                    <th>Email</th>
                                    <th>Address</th>
                                    <th>Phone</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                        </table>
                    </div>
                </div>
            </div>

            <!-- Modal -->
            <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <form id="employee-form" method="post">
                               
                                <div class="row">
                                    <div class="col-lg">
                                        <label>Name</label>
                                        <input type="text" name="name" id="name" class="form-control">
                                    </div>
                                    <div class="col-lg">
                                        <label>Email</label>
                                        <input type="email" name="email" id="email" class="form-control">
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-lg">
                                        <label>Address</label>
                                        <input type="text" name="address" id="address" class="form-control">
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-lg">
                                        <label>Phone</label>
                                        <input type="text" name="phone" id="phone" class="form-control">
                                    </div>
                                </div>
                            </form>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                            <button type="submit" class="btn btn-primary" form="employee-form">Save</button>
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </div>


    <div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="editModalLabel" aria-hidden="true">
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title" id="editModalLabel">Edit Employee</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <form id="edit-form" method="post">
                                <input type="hidden" id="edit-id" name="id">
                                <div class="row">
                                    <div class="col-lg">
                                        <label>Name</label>
                                        <input type="text" id="edit-name" name="name" class="form-control">
                                    </div>
                                    <div class="col-lg">
                                        <label>Email</label>
                                        <input type="email" id="edit-email" name="email" class="form-control">
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-lg">
                                        <label>Address</label>
                                        <input type="text" id="edit-address" name="address" class="form-control">
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-lg">
                                        <label>Phone</label>
                                        <input type="text" id="edit-phone" name="phone" class="form-control">
                                    </div>
                                </div>
                            </form>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                            <button type="submit" class="btn btn-primary" form="edit-form">Edit</button>
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <script src="https://cdn.datatables.net/2.1.2/js/dataTables.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>

    <script>
        $(document).ready(function () {
            var table = $('#myTable').DataTable({
                "ajax": {
                    "url": "{{ route('getall') }}",
                    "type": "GET",
                    "dataType": "json",
                    "headers": {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                    "dataSrc": function (response) {
                        if (response.status === 200) {
                            return response.employees;
                        } else {
                            return [];
                        }
                    }
                },
                "columns": [
                    { "data": "id" },
                    { "data": "name" },
                    { "data": "email" },
                    { "data": "address" },
                    { "data": "phone" },
                    {
                        "data": null,
                        "render": function (data, type, row) {
                            return '<a href="#" class="btn btn-sm btn-success edit-btn" data-id="'+data.id+'" data-name="'+data.name+'" data-email="'+data.email+'" data-address="'+data.address+'" data-phone="'+data.phone+'">Edit</a> ' +
                            '<a href="#" class="btn btn-sm btn-danger delete-btn" data-id="'+data.id+'">Delete</a>';


                        }
                    }
                ]
            });

            $('#myTable tbody').on('click', '.edit-btn', function () {
                var id = $(this).data('id');
                var name = $(this).data('name');
                var email = $(this).data('email');
                var address = $(this).data('address');
                var phone = $(this).data('phone');
              
                $('#edit-id').val(id);
                $('#edit-name').val(name);
                $('#edit-email').val(email);
                $('#edit-address').val(address);
                $('#edit-phone').val(phone);
                $('#editModal').modal('show');
            });


            $('#employee-form').submit(function (e) {
                e.preventDefault();
                const employeedata = new FormData(this);

                $.ajax({
                    url: '{{ route('store') }}',
                    method: 'post',
                    data: employeedata,
                    cache: false,
                    contentType: false,
                    processData: false,
                    dataType: 'json',
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                    success: function(response) {
                        if (response.status == 200) {
                            alert("Saved successfully");
                            $('#employee-form')[0].reset();
                            $('#exampleModal').modal('hide');
                            $('#myTable').DataTable().ajax.reload();
                        }
                    }
                });
            });

        });


        $('#edit-form').submit(function (e) {
                e.preventDefault();
                const employeedata = new FormData(this);

                $.ajax({
                    url: '{{ route('update') }}',
                    method: 'POST',
                    data: employeedata,
                    cache: false,
                    contentType: false,
                    processData: false,
                    dataType: 'json',
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                    success: function(response) {
                        if (response.status === 200) {
                            alert(response.message);
                            $('#edit-form')[0].reset();
                            $('#editModal').modal('hide');
                            $('#myTable').DataTable().ajax.reload();
                        } else {
                            alert(response.message);
                        }
                    }
                });
            });
        
            $(document).on('click', '.delete-btn', function() {
                var id = $(this).data('id');

                if (confirm('Are you sure you want to delete this employee?')) {
                    $.ajax({
                        url: '{{ route('delete') }}',
                        type: 'DELETE',
                        data: {id: id},
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        },
                        success: function(response) {
                            console.log(response); // Debugging: log the response
                            if (response.status === 200) {
                                alert(response.message); // Show success message
                                $('#myTable').DataTable().ajax.reload(); // Reload the table data
                            } else {
                                alert(response.message); // Show error message
                            }
                        },
                        error: function(xhr, status, error) {
                            console.error(xhr); // Debugging: log the error
                            alert('Error: ' + error); // Show generic error message
                        }
                    });
                }
            });

    </script>

</body>
</html>

Routes

Pages are Manage through routes. If you are crud system simple you can add it the routes one line look like this

<?php

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

Route::get('/', function () {
    return view('home');

});
Route::post('/store', [EmployeeController::class, 'store'])->name('store');
Route::get('/getall', [EmployeeController::class, 'getall'])->name('getall');
Route::get('/employee/{id}/edit', [EmployeeController::class, 'edit'])->name('edit');
Route::post('/employee/update', [EmployeeController::class, 'update'])->name('update');

Route::delete('/employee/delete', [EmployeeController::class, 'delete'])->name('delete');

 

 

 

Load More Related Articles
Load More By admin
Load More In Laravel 9

Leave a Reply

Your email address will not be published. Required fields are marked *

Check Also

How to Make a Admin Panel Using React MUI

I have design the Admin Basic templete using React MUI Design Admin Dashboard and Login.He…