How to Handle CRUD Requests using AJAX in Laravel 10

Last Updated on by in Laravel

AJAX, short for “Asynchronous JavaScript and XML,” revolutionizes web development by enabling data exchange between the web server and browser without full page reloads. AJAX dynamically updates page sections, enhancing responsiveness and speeding up load times.

Its ability to facilitate communication at distinct intervals allow developers to create seamless, real-time interactions, improving user experiences without requiring entire page refreshes, ultimately leading to more efficient and smoother web applications. 

Laravel streamlines AJAX integration by offering built-in support for handling asynchronous requests. Its features, like Eloquent ORM, simplify AJAX CRUD (Create, Read, Update, Delete) operations, allowing developers to efficiently manage data interactions between the server and client sides. 

In this tutorial, we will demonstrate how to handle CRUD requests in Laravel using AJAX, aiming to help web developers handle data asynchronously through HTTP requests and create dynamic and faster web applications. 

We’ll use jQuery for handling AJAX requests in relation to performing CRUD operations in Laravel, utilizing JSON responses to ensure efficient data exchange and guaranteeing smooth AJAX functionality within your application.

Let’s start coding …

Install Laravel Project

We have to run the given below command to install a fresh Laravel application, this app will be the sacred canon for Laravel Ajax example.

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

Head over to project directory, or you can simultaneously execute following command with above command followed by double && symbol.

cd laravel-ajax-crud

Make Database Connection

Ultimately, we have to define the database details in the .env file, make the consensus between laravel app and MySQL database.


If you are using MAMP, then you might possibly get the following migration error.

SQLSTATE[HY000] [2002] No such file or directory (SQL: select * from information_schema.tables where table_schema = laravel_db and table_name = migrations and table_type = ‘BASE TABLE’)

Paste the following line right after the database configuration inside the .env.


Create & Configure Model and Migration

We are creating a simple to-do application, this allows user to insert, read, update or delete the data from the database using AJAX requests.

In the model, we define the schema that communicates with the database. Whereas, migration set out to generate tables with values that interact with the model.

php artisan make:model Todo -m

The above command simultaneously created both Model and Migration file.

Add Values in Model

To set up the data values to the database, open app/Models/Todo.php and place the following code.


namespace App\Models;

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

class Todo extends Model
    use HasFactory;
    protected $fillable = ['title', 'description'];

Configure and Run Migration

To set up the data values to the database, open migrations/xxxx_xx_xx_xxxxxx_create_todos_table.php and place the following code.


use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateTodosTable extends Migration
     * Run the migrations.
     * @return void
    public function up()
        Schema::create('todos', function (Blueprint $table) {

     * Reverse the migrations.
     * @return void
    public function down()

Run Migration

We have added name and description values respectively and consecutively. Now, we have to define the todo app values within the up() function, so when we run the migration, then all the set values can be seen in the database.

php artisan migrate

Create Controller

Execute the following command to create the controller for handling CRUD logic.

php artisan make:controller CrudController

Paste the following code in the newly created controller in app/Http/Controllers/CrudController.php file.


namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Response;
use App\Models\Todo;

class CrudController extends Controller {

     * Display a listing of the resource.
    public function index()
        $todo = Todo::all();
        return view('home')->with(compact('todo'));

     * Store a newly created resource in storage.
    public function store(Request $request)
        $data = $request->validate([
            'title' => 'required|max:255',
            'description' => 'required'
        $todo = Todo::create($data);

        return Response::json($todo);


Generically, create two functions here, and these functions propel the Laravel AJAX example. The index function renders all the records from the database, and preferably store method saves the data record in the database.

Create Routes

Define route; it is one of the foundational steps that directly communicates with the controller that we created earlier, open routes/web.php, and paste the following code.


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

| 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('/', [CrudController::class, 'index']);

Route::resource('todo', CrudController::class);

Create Layout

Let us create the view for showing you how to use AJAX in the Laravel application precisely. Head over to resources/views folder and create home.blade.php file.

After creating the recommended file, also create views/layouts/app.blade.php file and folder. Add the following code inside the app.blade.php file.

<!DOCTYPE html>
<html lang="en">

    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>Laravel AJAX CRUD Example</title>
    <link rel="stylesheet" href="">

<body class="container mt-5">


    <script src=""></script>
    <script src=""></script>
    <script src="{{ asset('js/todo.js') }}" defer></script>



Make Ajax request in Laravel

First, we have to create the table layout and modal popup with form using Bootstrap. These two foundational elements are useful in propelling the AJAX request in Laravel to render or store the data in the database.

Insert the following code in views/home.blade.php file.



<div class="container">

    <div class="d-flex bd-highlight mb-4">
        <div class="p-2 w-100 bd-highlight">
            <h2>Laravel AJAX Example</h2>
        <div class="p-2 flex-shrink-0 bd-highlight">
            <button class="btn btn-success" id="btn-add">
                Add Todo

        <table class="table table-inverse">
            <tbody id="todos-list" name="todos-list">
                @foreach ($todo as $data)
                <tr id="todo{{$data->id}}">

        <div class="modal fade" id="formModal" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h4 class="modal-title" id="formModalLabel">Create Todo</h4>
                    <div class="modal-body">
                        <form id="myForm" name="myForm" class="form-horizontal" novalidate="">

                            <div class="form-group">
                                <input type="text" class="form-control" id="title" name="title"
                                        placeholder="Enter title" value="">

                            <div class="form-group">
                                    <input type="text" class="form-control" id="description" name="description"
                                        placeholder="Enter Description" value="">
                    <div class="modal-footer">
                        <button type="button" class="btn btn-primary" id="btn-save" value="add">Save changes
                        <input type="hidden" id="todo_id" name="todo_id" value="0">



AJAX Logic in Laravel

Now, we need to create a todo.js file inside the public/js folder. Place the entire code in it.


    //----- Open model CREATE -----//
    jQuery('#btn-add').click(function () {

    // CREATE
    $("#btn-save").click(function (e) {
            headers: {
                'X-CSRF-TOKEN': jQuery('meta[name="csrf-token"]').attr('content')
        var formData = {
            title: jQuery('#title').val(),
            description: jQuery('#description').val(),
        var state = jQuery('#btn-save').val();
        var type = "POST";
        var todo_id = jQuery('#todo_id').val();
        var ajaxurl = 'todo';
            type: type,
            url: ajaxurl,
            data: formData,
            dataType: 'json',
            success: function (data) {
                var todo = '<tr id="todo' + + '"><td>' + + '</td><td>' + data.title + '</td><td>' + data.description + '</td>';
                if (state == "add") {
                } else {
                    jQuery("#todo" + todo_id).replaceWith(todo);
            error: function (data) {

Test Laravel AJAX App

You need to start the application by executing the below command:

php artisan serve

You can test the app on the following URL:

You can check out the working example of Laravel and AJAX application.

Add Data

Laravel AJAX Demo

List View

Laravel Ajax List view Example


In this tutorial, We’ve learned how to use AJAX in Laravel, and step-by-step covered:

How to use AJAX to create new database records, handle form submissions asynchronously, and fetch data from the server and display it dynamically.

Also looked at, how to use AJAX requests to edit existing records, update data in real-time without reloading the entire page, and remove or delete records from the database.