Laravel 9 Ajax CRUD Operation with Datatable and Bootstrap Model

Throughout this Laravel 9 ajax crud operation explain you how to build ajax CRUD with yajra datatable and bootstrap model example in laravel 9 application.

As you know laravel 9 was released with many new features and functionality. So, today we will see how to make laravel 9 Ajax CRUD tutorial with a simple example.

In web application many times you need to create Ajax CRUD for insert, update, delete or listing database data in frontend. if you don’t want to page load when you insert, update, delete data then you should use Ajax in your laravel application and it is very smooth.

Laravel 9 Ajax CRUD Example Tutorial

In this post we will cover the following steps to implement laravel Vue.js CRUD App example:

  • Step 1 : Install laravel 9 application.
  • Step 2 : Setup database credentials
  • Step 3 : Create Post model and migration
  • Step 4 : Create routes
  • Step 5 : Create Controller
  • Step 6 : Create Blade files
  • Step 7 : Add Bootstrap Models
  • Step 8 : Add JS & Ajax Request

Install Laravel 9 App

First, we need to create one fresh laravel application help of the composer command. just run the following command in your terminal and create one laravel application.

composer create-project --prefer-dist laravel/laravel laravelajax

Configure Database Credentials

Now, into the second step, we should configure the database settings in .env file just open your .env file and make the following changes. set youe database name, username, and password.

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

Create Model and Run Migration

For generating model and migration you need to run the below command.

php artisan make:model Post -m

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

In Migration file

In your migration file update the table columns just like below.

database\migrations\2021_03_21_061250_create_posts_table.php

<?php

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

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

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

After this run the below command

php artisan migrate

Update Fillable Properties in Model

In your model app\Post.php add fallible property same like below.

<?php

namespace App\Models;

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

class Post extends Model
{
    use HasFactory;

    protected $fillable = [
      'title', 'description'
    ];
}

Define Routes

Now update the laravel 8 crud with ajax routes same like below.

routes/web.php

<?php

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

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

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

Create Controller

Now create new controller as PostController just running below command.

php artisan make:controller PostController --resource

After successfully created controller add below methods on it.

app/Http/Controllers/PostController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Post;

class PostController extends Controller
{
  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function index()
  {
      $posts = Post::all();

      return view('posts', ['posts' => $posts]);
  }

  /**
   * 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);

  }

  /**
   * 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  int  $id
   * @return \Illuminate\Http\Response
   */
  public function destroy($id)
  {
    $post = Post::find($id)->delete();

    return response()->json(['success'=>'Post Deleted successfully']);
  }
}

Create Blade File

In this step create posts.blade.php blade file and put below code on it.

resources\views\posts.blade.php

<!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 JS and Send Ajax Request

Now add jquery and ajax code after closing in body tag for laravel 8 ajax crud.

<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>

After done this all steps then your posts Ajax CRUD is ready to run and test it is working fine or not? just run the below command in your project root directory for run the laravel application in web browser.

php artisan serve

Then open your web browser and hit the following url in the browser.

https://localhost:8000/posts

So, guys the Laravel 8 AJAX CRUD Example Tutorial from Scratch is over now. If you have any issues or query about ajax crud with laravel please comment us. Follow us on twitter for more update’s.

Leave a Comment