Laravel 8 AJAX CRUD Using Datatable

In this article, we will see the laravel 8 AJAX CRUD operation using datatable. we will perform the AJAX CRUD operation without page refresh. If you don't want to page reload when you insert, update, or delete data then you should use AJAX call in your laravel 8. Also, we will see how to use yajra datatables in laravel 8. We can use yajra datatable to perform an AJAX CRUD operation in laravel 8. So, follow step-by-step AJAX CRUD operation PHP.

Laravel 8 Ajax CRUD Operation Example Tutorial

Step 1: Create Laravel 8 Application

Step 2: Setup Database Configuration

Step 3: Create Migration and Model

Step 4: Install yajra/laravel-datatables Package

Step 5: Add Resource Route

Step 6: Add Controller and Model

Step 7: Add Blade Files

 

Step 1: Create Laravel 8 Application

In this step, we will create larave 8 application using the following command.

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

 

 

Step 2: Setup Database Configuration

In this step, we will configure a database. So, open the .env file and add the following details.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_database_username
DB_PASSWORD=your_database_password

 

Step 3: Create Migration and Model

Now, we will create migration for the "posts" table. So, run the following command and create a post table.

php artisan make:migration create_posts_table --create=posts

After running this command you will find a PHP file here location "database/migrations/" in this file you need to add the below code.

<?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->longText('description')->nullable();
            $table->timestamps();
        });
    }

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

After this, we need to run migration using the following command.

php artisan migrate

 

 

Step 4: Install yajra/laravel-datatables package

Now, we will install yajra/laravel-datatables in our project. So, run the following command in your terminal.

composer require yajra/laravel-datatables-oracle

 

Step 5: Add Resource Route

Now, Add the route in the routes/web.php file.

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

Route::resource('ajaxposts', PostAjaxController::class);

 

Step 6: Add Controller and Model

In this step, we will create the PostAjaxController using the following command.

php artisan make:controller PostAjaxController --resource --model=Post

Now, we will add the field's name to the model.

app/Models/Post.php

<?php
  
namespace App\Models;
  
use Illuminate\Database\Eloquent\Model;
   
class Post extends Model
{
    protected $fillable = [
        'id', 'title', 'description'
    ];
}

 

 

app/Http/Controllers/PostAjaxController.php

<?php
         
namespace App\Http\Controllers;
          
use App\Models\Post;
use Illuminate\Http\Request;
use DataTables;
        
class PostAjaxController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
   
        if ($request->ajax()) {
            $post = Post::latest()->get();
            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="Edit" class="edit btn btn-primary btn-sm editPost">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 deletePost">Delete</a>';
    
                            return $btn;
                    })
                    ->rawColumns(['action'])
                    ->make(true);
        }
      
        return view('postAjax',compact('post'));
    }
     
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        Post::updateOrCreate(['id' => $request->id],
                ['title' => $request->title, 'description' => $request->description]);        
   
        return response()->json(['success'=>'Post saved successfully.']);
    }
    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Post
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $post = Post::find($id);
        return response()->json($post);
    }
  
    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Post
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        Post::find($id)->delete();
     
        return response()->json(['success'=>'Post deleted successfully.']);
    }
}

 

 

Step 7: Add Blade Files

In this step, we will create blade files. So, create postAjax.blade.php in this path resources/views/postAjax.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 8 AJAX CRUD Using Datatable - Techsolutionstuff</title>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>
    <link href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css" rel="stylesheet">
    <script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
    <link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet">
    <script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>  
</head>
<body>
    
<div class="container">
    <h1>Laravel 8 AJAX CRUD Using Datatable - Techsolutionstuff</h1>
    <a class="btn btn-info" href="javascript:void(0)" id="createNewPost"> Add New Post</a>
    <table class="table table-bordered data-table">
        <thead>
            <tr>
                <th>No</th>
                <th>Title</th>
                <th>Description</th>
                <th width="280px">Action</th>
            </tr>
        </thead>
        <tbody>
        </tbody>
    </table>
</div>
   
<div class="modal fade" id="ajaxModelexa" 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="postForm" name="postForm" class="form-horizontal">
                   <input type="hidden" name="id" id="id">
                    <div class="form-group">
                        <label for="title" class="col-sm-2 control-label">Title</label>
                        <div class="col-sm-12">
                            <input type="text" class="form-control" id="title" name="title" placeholder="Enter Name" value="" required>
                        </div>
                    </div>
     
                    <div class="form-group">
                        <label class="col-sm-2 control-label">Description</label>
                        <div class="col-sm-12">
                            <textarea id="description" name="description" required placeholder="Enter Description" class="form-control"></textarea>
                        </div>
                    </div>
      
                    <div class="col-sm-offset-2 col-sm-10">
                     <button type="submit" class="btn btn-primary" id="savedata" value="create">Save Post
                     </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
    
</body>
    
<script type="text/javascript">
  $(function () {
     
      $.ajaxSetup({
          headers: {
              'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          }
    });
    
    var table = $('.data-table').DataTable({
        processing: true,
        serverSide: true,
        ajax: "{{ route('ajaxposts.index') }}",
        columns: [
            {data: 'DT_RowIndex', name: 'DT_RowIndex'},
            {data: 'title', name: 'title'},
            {data: 'description', name: 'description'},
            {data: 'action', name: 'action', orderable: false, searchable: false},
        ]
    });
     
    $('#createNewPost').click(function () {
        $('#savedata').val("create-post");
        $('#id').val('');
        $('#postForm').trigger("reset");
        $('#modelHeading').html("Create New Post");
        $('#ajaxModelexa').modal('show');
    });
    
    $('body').on('click', '.editPost', function () {
      var id = $(this).data('id');
      $.get("{{ route('ajaxposts.index') }}" +'/' + id +'/edit', function (data) {
          $('#modelHeading').html("Edit Post");
          $('#savedata').val("edit-user");
          $('#ajaxModelexa').modal('show');
          $('#id').val(data.id);
          $('#title').val(data.title);
          $('#description').val(data.description);
      })
   });
    
    $('#savedata').click(function (e) {
        e.preventDefault();
        $(this).html('Sending..');
    
        $.ajax({
          data: $('#postForm').serialize(),
          url: "{{ route('ajaxposts.store') }}",
          type: "POST",
          dataType: 'json',
          success: function (data) {
     
              $('#postForm').trigger("reset");
              $('#ajaxModelexa').modal('hide');
              table.draw();
         
          },
          error: function (data) {
              console.log('Error:', data);
              $('#savedata').html('Save Changes');
          }
      });
    });
    
    $('body').on('click', '.deletePost', function () {
     
        var id = $(this).data("id");
        confirm("Are You sure want to delete this Post!");
      
        $.ajax({
            type: "DELETE",
            url: "{{ route('ajaxposts.store') }}"+'/'+id,
            success: function (data) {
                table.draw();
            },
            error: function (data) {
                console.log('Error:', data);
            }
        });
    });
     
  });
</script>
</html>

Copy the below command and run it in the terminal.

php artisan serve

 

 

Then open your web browser and add the following URL to the browser.

http://localhost:8000/ajaxposts

 


You might also like:

RECOMMENDED POSTS

FEATURE POSTS