Laravel 10 AJAX CRUD Example Step By Step

Implementing AJAX CRUD in Laravel allows you to perform Create, Read, Update, and Delete operations on your database without reloading the entire page. Here’s a step-by-step guide on how to implement AJAX CRUD in Laravel 10.

AJAX (Asynchronous JavaScript and XML) is a powerful technology that allows web applications to communicate with a server in the background without refreshing the page. Let’s see the below example on how you can implement AJAX CRUD in your Laravel application:

Laravel Ajax CRUD Example

In Laravel, you can use AJAX to perform CRUD (Create, Read, Update, Delete) operations without reloading the entire page. Use the following steps to create laravel Ajax crud with popup modal using dataTable js without refresh and search sort functionality:

  • Step 1: Set up a Laravel project
  • Step 2: Connect Database with App
  • Step 3: Create Model & Migration
  • Step 4: Make Routes
  • Step 5: Create Controller
  • Step 6: Create Blade Views File
  • Step 7: Add Bootstrap Model
  • Step 8: Add Datatable & Ajax Request
  • Step 9: Run Development Server

Set up a Laravel project

If you haven’t already set up a Laravel project, create a new project using the following command in your terminal:

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

Go inside the project:

cd laravcel-ajax-crud

Connect Database to App

Create a new database for your project and configure the database connection details in the .env file located in the root directory of your Laravel project.

 DB_CONNECTION=mysql 
 DB_HOST=127.0.0.1 
 DB_PORT=3306 
 DB_DATABASE=your database name here
 DB_USERNAME=database username here
 DB_PASSWORD=database password here

Create Model and Migration

Now run below command and get a model Post and migration file for generating database table:

php artisan make:model Post -m

After running this command you will get one model file Post.php and one migration file.

Check in your database\migrations directory and open the newly created file where you need to add your database column just like below.

<?php

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

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('title')->nullable();
            $table->text('description')->nullable();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}
php artisan migrate

Update fillable properties in Model

Next, open your model app\Models\Post.php add fallible property same like below.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    public $fillable = ['title', 'description'];
}

Create Routes

Define the routes for your CRUD operations in the routes/web.php file. Here’s an example:

use App\Controllers\PostController;

Route::resource('posts', 'PostController');

Create Controller

Create a controller to handle the CRUD operations. Run the following command to generate a controller:

php artisan make:controller PostController --resource

After successfully created controller, now open the app/Http/Controllers/PostController.php file and put the methods on it;

<?php

namespace App\Http\Controllers;

use App\Post;
use Illuminate\Http\Request;
use Redirect,Response;

class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data['posts'] = Post::orderBy('id','desc')->paginate(8);

        return view('posts', $data);
    }


    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
     public function store(Request $request)
     {
         $request->validate([
           'title'       => 'required|max:255',
           'description' => 'required',
         ]);

         $post = Post::updateOrCreate(['id' => $request->id], [
                   'title' => $request->title,
                   'description' => $request->description
                 ]);

         return response()->json(['code'=>200, 'message'=>'Post Created successfully','data' => $post], 200);

     }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $post = Post::find($id);

        return Response::json($post);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $post = Post::find($id);

        return response()->json($post);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $post= Post::find($id)->delete();

        return Response::json($post);
    }
}

Create Blade File

In this step create posts.blade.php blade file in your resources/views directory and then open the resources\views\posts.blade.php file and update the below code on it;

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <meta name="csrf-token" content="{{ csrf_token() }}">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
  <link rel="stylesheet" href="https://cdn.datatables.net/r/bs-3.3.5/jq-2.1.4,dt-1.10.8/datatables.min.css"/>

  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
  <script src="https://cdn.datatables.net/r/bs-3.3.5/jqc-1.11.3,dt-1.10.8/datatables.min.js"></script>

</head>
  <style>
  .alert-message {
    color: red;
  }
</style>
<body>

<div class="container">
    <h2 style="margin-top: 12px;" class="alert alert-success">Ajax CRUD with Laravel App -
       <a href="https://www.codingdriver.com" target="_blank" >CodingDriver</a>
     </h2><br>
     <div class="row">
       <div class="col-12 text-right">
         <a href="javascript:void(0)" class="btn btn-success mb-3" id="create-new-post" onclick="addPost()">Add Post</a>
       </div>
    </div>
    <div class="row" style="clear: both;margin-top: 18px;">
        <div class="col-12">
          <table id="laravel_crud" class="table table-striped table-bordered">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Title</th>
                    <th>Description</th>
                    <th>Edit</th>
                    <th>Delete</th>
                </tr>
            </thead>
            <tbody>
                @foreach($posts as $post)
                <tr id="row_{{$post->id}}">
                   <td>{{ $post->id  }}</td>
                   <td>{{ $post->title }}</td>
                   <td>{{ $post->description }}</td>
                   <td><a href="javascript:void(0)" data-id="{{ $post->id }}" onclick="editPost(event.target)" class="btn btn-info">Edit</a></td>
                   <td>
                    <a href="javascript:void(0)" data-id="{{ $post->id }}" class="btn btn-danger" onclick="deletePost(event.target)">Delete</a></td>
                </tr>
                @endforeach
            </tbody>
          </table>
       </div>
    </div>
</div>
</body>
</html>

Add Bootstrap Model

After adding the posts blade file now add a model after last closing div. If you have any issue you can ask below command.

<div class="modal fade" id="post-modal" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
        <div class="modal-header">
            <h4 class="modal-title"></h4>
        </div>
        <div class="modal-body">
            <form name="userForm" class="form-horizontal">
               <input type="hidden" name="post_id" id="post_id">
                <div class="form-group">
                    <label for="name" class="col-sm-2">title</label>
                    <div class="col-sm-12">
                        <input type="text" class="form-control" id="title" name="title" placeholder="Enter title">
                        <span id="titleError" class="alert-message"></span>
                    </div>
                </div>

                <div class="form-group">
                    <label class="col-sm-2">Description</label>
                    <div class="col-sm-12">
                        <textarea class="form-control" id="description" name="description" placeholder="Enter description" rows="4" cols="50">
                        </textarea>
                        <span id="descriptionError" class="alert-message"></span>
                    </div>
                </div>
            </form>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-primary" onclick="createPost()">Save</button>
        </div>
    </div>
  </div>
</div>

Add Datatable & Ajax Request for Search and Sort

Now add jquery and ajax code after closing in body tag.

<script>
  $('#laravel_crud').DataTable();

  function addPost() {
    $("#post_id").val('');
    $('#post-modal').modal('show');
  }

  function editPost(event) {
    var id  = $(event).data("id");
    let _url = `/posts/${id}`;
    $('#titleError').text('');
    $('#descriptionError').text('');

    $.ajax({
      url: _url,
      type: "GET",
      success: function(response) {
          if(response) {
            $("#post_id").val(response.id);
            $("#title").val(response.title);
            $("#description").val(response.description);
            $('#post-modal').modal('show');
          }
      }
    });
  }

  function createPost() {
    var title = $('#title').val();
    var description = $('#description').val();
    var id = $('#post_id').val();

    let _url     = `/posts`;
    let _token   = $('meta[name="csrf-token"]').attr('content');

      $.ajax({
        url: _url,
        type: "POST",
        data: {
          id: id,
          title: title,
          description: description,
          _token: _token
        },
        success: function(response) {
            if(response.code == 200) {
              if(id != ""){
                $("#row_"+id+" td:nth-child(2)").html(response.data.title);
                $("#row_"+id+" td:nth-child(3)").html(response.data.description);
              } else {
                $('table tbody').prepend('<tr id="row_'+response.data.id+'"><td>'+response.data.id+'</td><td>'+response.data.title+'</td><td>'+response.data.description+'</td><td><a href="javascript:void(0)" data-id="'+response.data.id+'" onclick="editPost(event.target)" class="btn btn-info">Edit</a></td><td><a href="javascript:void(0)" data-id="'+response.data.id+'" class="btn btn-danger" onclick="deletePost(event.target)">Delete</a></td></tr>');
              }
              $('#title').val('');
              $('#description').val('');

              $('#post-modal').modal('hide');
            }
        },
        error: function(response) {
          $('#titleError').text(response.responseJSON.errors.title);
          $('#descriptionError').text(response.responseJSON.errors.description);
        }
      });
  }

  function deletePost(event) {
    var id  = $(event).data("id");
    let _url = `/posts/${id}`;
    let _token   = $('meta[name="csrf-token"]').attr('content');

      $.ajax({
        url: _url,
        type: 'DELETE',
        data: {
          _token: _token
        },
        success: function(response) {
          $("#row_"+id).remove();
        }
      });
  }

</script>

Run Your Application

The last step, open the command prompt and run the following command to start developement server:

php artisan serve

Then open your browser and hit the following url on it:

http://127.0.0.1:8000/posts

or
http://localhost:8000/posts

So, guys the Laravel AJAX CRUD Example Tutorial from Scratch is over now. You have successfully implemented AJAX CRUD in Laravel application.

16 thoughts on “Laravel 10 AJAX CRUD Example Step By Step”

  1. Thanks for the Tutorials.
    But i want to add DataTables().draw() after success submitting form, but its nor working.
    Do you have solution ?

    Reply
    • Hey I think you doning something wrong, This example is fully by me, Can you please send error which api request sent this type of error

      Reply

Leave a Comment