DEV Community

Story Coding
Story Coding

Posted on

CARA PAKAI DATATABLES SERVER-SIDE DI LARAVEL

Berikut alurnya:

1) Install Laravel DataTables (by Yajra)
Jalankan:

composer require yajra/laravel-datatables-oracle
Enter fullscreen mode Exit fullscreen mode

Lalu publish config:

php artisan vendor:publish --tag=datatables
Enter fullscreen mode Exit fullscreen mode

2) Buat Route Khusus untuk AJAX DataTables

use App\Http\Controllers\PostController;

Route::get('post/data', [PostController::class, 'getData'])->name('post.data');
Route::resource('post', PostController::class);
Enter fullscreen mode Exit fullscreen mode

3) Tambahkan Method getData() di PostController

use Yajra\DataTables\Facades\DataTables;

public function getData(Request $request)
{
    $posts = Post::select(['id', 'judul', 'slug', 'created_at']);

    return DataTables::of($posts)
        ->addColumn('action', function ($post) {
            return '
                <a href="' . route('post.edit', $post) . '">Edit</a> |
                <a href="' . route('post.show', $post) . '">Lihat</a>
            ';
        })
        ->rawColumns(['action'])
        ->make(true);
}
Enter fullscreen mode Exit fullscreen mode

4) Update post/index.blade.php Pakai AJAX DataTables

@extends('layouts.app')

@section('content')
    <h1>Daftar Post</h1>
    <a href="{{ route('post.create') }}">Buat Post Baru</a>

    <table id="post-table" class="display">
        <thead>
            <tr>
                <th>ID</th>
                <th>Judul</th>
                <th>Slug</th>
                <th>Dibuat</th>
                <th>Aksi</th>
            </tr>
        </thead>
    </table>
@endsection

@section('scripts')
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
    $('#post-table').DataTable({
       processing: true,
       serverSide: true,
       ajax: '{{ route('post.data') }}',
       lengthMenu: [10, 25, 50, 100], // << ini penting
       pageLength: 10,
       columns: [
          { data: 'id', name: 'id' },
          { data: 'judul', name: 'judul' },
          { data: 'slug', name: 'slug' },
          { data: 'created_at', name: 'created_at' },
          { data: 'action', name: 'action', orderable: false, searchable: false },
       ]
    });

});
</script>
@endsection
Enter fullscreen mode Exit fullscreen mode

Jangan lupa juga tambahkan @yield(’scripts’) di layouts.app.blade.php sebelum </body>:

@yield('scripts')
</body>
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
navin_sio_776158732e184bf profile image
Navin Sio

Hello
Nice to meet you
Could you help me