Berikut alurnya:
1) Install Laravel DataTables (by Yajra)
Jalankan:
composer require yajra/laravel-datatables-oracle
Lalu publish config:
php artisan vendor:publish --tag=datatables
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);
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);
}
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
Jangan lupa juga tambahkan @yield(’scripts’)
di layouts.app.blade.php sebelum </body>
:
@yield('scripts')
</body>
Top comments (1)
Hello
Nice to meet you
Could you help me