Laravel 使用 yajra/laravel-datatables-oracle 建立資料表格

介紹

使用 yajra/laravel-datatables-oracle 套件,可以在 Laravel 中快速整合 DataTables 前端元件,無需手動編寫繁瑣的 JavaScript 或處理伺服器端資料處理邏輯。

特點包括:

  • 支援 AJAX 載入資料
  • 自動伺服器端處理 (Server-side processing)
  • 具備分頁、排序、搜尋等功能
  • 可搭配 Eloquent、Query Builder 或 Collection 作為資料來源
  • 支援自定義欄位格式與列操作

安裝套件

composer require yajra/laravel-datatables-oracle

適用 Laravel 6 以上版本,請參考對應 官方安裝指南


發佈設定檔(可選)

php artisan vendor:publish --tag=datatables

此步驟為選用,僅在需要修改預設設定檔時才需執行。


控制器中建立資料表處理

use App\Models\User;
use Yajra\DataTables\DataTables;

public function index(Request $request)
{
    if ($request->ajax()) {
        return DataTables::of(User::query())->make(true);
    }

    return view('users.index');
}

確保僅當請求為 AJAX 時才回傳 JSON 結果,其餘返回 Blade 頁面。


建立 Blade 視圖 (resources/views/users/index.blade.php)

<table id="users-table" class="table table-bordered">
    <thead>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Email</th>
            <!-- 可加入更多欄位 -->
        </tr>
    </thead>
</table>

使用 jQuery 初始化 DataTables

<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script>
    $(function () {
        $('#users-table').DataTable({
            processing: true,
            serverSide: true,
            ajax: '{{ route('users.index') }}',
            columns: [
                { data: 'id', name: 'id' },
                { data: 'name', name: 'name' },
                { data: 'email', name: 'email' }
            ]
        });
    });
</script>

建議載入 DataTables 的 CDN 或使用 Laravel Mix 打包本地 JS。
processing: true 可顯示載入動畫,利於用戶體驗。


設定路由

use App\Http\Controllers\UserController;

Route::get('/users', [UserController::class, 'index'])->name('users.index');

補充:常見自定義操作

加入操作按鈕欄位:

控制器中:

DataTables::of(User::query())
    ->addColumn('action', function ($user) {
        return '<a href="'.route('users.edit', $user->id).'" class="btn btn-sm btn-primary">編輯</a>';
    })
    ->rawColumns(['action']) // 記得標示為 raw HTML 欄位
    ->make(true);

視圖 columns 設定:

{ data: 'action', name: 'action', orderable: false, searchable: false }

延伸閱讀