惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Google DeepMind News
Google DeepMind News
Microsoft Security Blog
Microsoft Security Blog
B
Blog
Martin Fowler
Martin Fowler
WordPress大学
WordPress大学
爱范儿
爱范儿
博客园_首页
博客园 - 聂微东
量子位
V
Visual Studio Blog
aimingoo的专栏
aimingoo的专栏
T
The Blog of Author Tim Ferriss
J
Java Code Geeks
小众软件
小众软件
大猫的无限游戏
大猫的无限游戏
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
N
Netflix TechBlog - Medium
F
Fortinet All Blogs
The Cloudflare Blog
T
Tailwind CSS Blog
G
Google Developers Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
月光博客
月光博客
腾讯CDC

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Server-Side DataTables Rendering in Laravel
Rafli Zocky · 2026-05-11 · via DEV Community
Cover image for Server-Side DataTables Rendering in Laravel

Rafli Zocky

Aside from doing indexes, and use join() instead of with(). This example uses the DataTables library.

<link rel="stylesheet" href="https://cdn.datatables.net/2.3.7/css/dataTables.dataTables.css" />  
<script src="https://cdn.datatables.net/2.3.7/js/dataTables.js"></script>

Enter fullscreen mode Exit fullscreen mode

1. Route

Route::post('/data', [App\Http\Controllers\MyController::class, 'datatable'])->name('mydata.datatable');

Enter fullscreen mode Exit fullscreen mode

2. View

Date input, datatable, and button.

<div class="mb-4 form-group col-lg-4">
    <label class="form-label">Start Date</label>
    <input type="text" name="start_date" id="start_date" class="form-control" required>
</div>
<div class="mb-4 form-group col-lg-4">
    <label class="form-label">End Date</label>
    <input type="text" name="end_date" id="end_date" class="form-control" required>
</div>
<div class="mb-4 form-group col-lg-4">
    <button class="btn btn-sm btn-light-primary font-weight-bold" id="btnShow">Show</button>
</div>

<table class="table table-hover table-bordered table-vertical-center" id="tableMyData">
    <thead class="table-success font-weight-bold">
        <tr>
            <th class='text-left'>INVOICE</th>
            <th class='text-left'>AMOUNT</th>
        </tr>
    </thead>
    <tbody style="white-space: nowrap;"></tbody>
</table>

<script>
  $('#btnTampilkan').on('click', function() {
      _loadMyData();
  });

  let table;
  function _loadMyData() {
      var start = $('#start_date').val(); 
      var end = $('#end_date').val(); 
      if (table) table.destroy();
      if (!start || !end) return Swal.fire('Warning', 'Start & End date is required!', 'warning');
      table = $('#tableMyData').DataTable({
          processing: true,
          autoWidth: false,
          serverSide: true,
          pagingType: 'full_numbers',
          lengthMenu: [[10, 20, 50, 100], [10, 20, 50, 100]],
          pageLength: 10,
          destroy: true,
          ajax: {
              url: "{{ route('mydata.datatable') }}",
              type: 'POST',
              data: {
                  start_date: start,
                  end_date: end,
                  _token: "{{ csrf_token() }}"
              }
          },
          language: {
              emptyTable: "No data found"
          },
          order: [[1, 'desc']],
          columnDefs: [
              { orderable: false, targets: 0, width: '3%' },
          ],
          columns: [
              {
                  data: null,
                  render: (data) => `<input type="checkbox" class="row-checkbox" data-nosep="${data.nosep}">`
              },
              { data: 'invoice' },
              { data: 'amount' },
          ],
          // search delay
          initComplete() {
              const api = this.api();
              let typingTimer;
              $('#tableMyData_filter input').off().on('keyup', function (e) {
                  clearTimeout(typingTimer);
                  const value = this.value;
                  if (e.which === 13) {
                      api.search(value).draw();
                  } else {
                      typingTimer = setTimeout(() => api.search(value).draw(), 500);
                  }
              });
          }
      });
  }
</script>

Enter fullscreen mode Exit fullscreen mode

3. Controller

use Illuminate\Http\Request;

public function datatable(Request $request)
{
    $query = ...
        ->whereBetween('order_date', [$request->start, $request->end]);

    $maxLimit = 100000;
    $columns = [null, 'invoice', 'amount'];

    $recordsTotal = min((clone $query)->count(), $maxLimit);
    // SEARCH
    if ($search = $request->input('search.value')) {
        $normalized = str_replace(['.', ','], '', $search);
        $query->where(function($q) use ($search, $normalized) {
            $q->where('invoice', 'LIKE', "%{$search}%")
              ->orWhere('amount', 'LIKE', "%{$search}%");
        });
    }

    $recordsFiltered = min((clone $query)->count(), $maxLimit);

    // ORDERING
    $order = $request->input('order', []);
    if ($order && ($col = $columns[$order[0]['column']] ?? null)) {
        $query->orderBy($col, $order[0]['dir'] ?? 'ASC');
    } else {
        $query->orderBy('order_date', 'ASC');
    }

    // PAGINATION
    $start = $request->input('start');
    $results = $start >= $maxLimit
        ? collect()
        : $query->offset($start)
                ->limit(min($request->input('length'), $maxLimit - $start))
                ->get();

    return response()->json([
        'draw' => intval($request->draw),
        'recordsTotal' => $recordsTotal,
        'recordsFiltered' => $recordsFiltered,
        'data' => $results->map(fn($r) => [
            'invoice' => $r->invoice,
            'amount' => $r->amount,
        ])
    ]);
}

Enter fullscreen mode Exit fullscreen mode

Need help building your app? I’m available for freelance web & Android development — raflizocky.netlify.app

☕ Support my writing: paypal.me/raflizocky · saweria.co/raflizocky