Skip to content

Instantly share code, notes, and snippets.

@jpalala
Created September 6, 2025 01:16
Show Gist options
  • Save jpalala/72465d27864d8a8bc2d49018447269c3 to your computer and use it in GitHub Desktop.
Save jpalala/72465d27864d8a8bc2d49018447269c3 to your computer and use it in GitHub Desktop.
solving the problem with yajra datatable

Yes, it's definitely possible to present a Laravel API resource as a paginated DataTable, and libraries like Yajra DataTable make this process significantly easier!

You're on the right track by mentioning Yajra DataTable. It's a very popular and powerful package that handles exactly what you're looking to achieve.

Here's a general overview of how you'd approach this in Laravel using Yajra DataTable:

1. Install Yajra DataTable:

First, you'll need to install the package via Composer:

composer require yajra/laravel-datatables-oracle

2. Create a Resource Controller:

You'll need a controller to handle the API requests for your DataTable. Let's say you have a Post model:

php artisan make:controller PostController

3. Define your API Resource:

If you haven't already, create an API resource for your model. This defines how your data will be structured in the API response.

php artisan make:resource PostResource

Then, in app/Http/Resources/PostResource.php:

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class PostResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'body' => $this->body,
            'created_at' => $this->created_at->format('Y-m-d H:i:s'),
            'updated_at' => $this->updated_at->format('Y-m-d H:i:s'),
            // Add any other fields you want to display
        ];
    }
}

4. Implement DataTable Logic in your Controller:

In your PostController, you'll use Yajra DataTable to fetch and return the data.

<?php

namespace App\Http\Controllers;

use App\Models\Post;
use App\Http\Resources\PostResource;
use Illuminate\Http\Request;
use Yajra\DataTables\DataTables;

class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        if ($request->ajax()) {
            $posts = Post::query(); // Eloquent query builder
            return DataTables::of(PostResource::collection($posts))
                ->addIndexColumn() // Add a column for the row index
                ->rawColumns(['action']) // If you have action buttons
                ->make(true);
        }

        // For the initial HTML load, you might return a view
        return view('posts.index'); // Assuming you have a posts/index.blade.php
    }
}

Explanation:

  • if ($request->ajax()): This ensures that the DataTable logic only runs when an AJAX request is made by the JavaScript on the frontend.
  • Post::query(): This starts an Eloquent query for your Post model. You can add any necessary where clauses, orderBy, etc. here.
  • PostResource::collection($posts): This applies your API resource to the collection of posts, formatting them as defined in PostResource.php.
  • DataTables::of(...): This is the core of Yajra DataTable. It takes your data (which is already formatted by the resource) and prepares it for DataTable.
  • ->addIndexColumn(): This adds a sequential number to each row, which is often useful.
  • ->rawColumns(['action']): If you plan to add buttons or links in your DataTable (e.g., "Edit", "Delete"), you'll need this to render them as HTML.
  • ->make(true): This triggers the DataTable processing and returns the JSON response that the JavaScript DataTable on the frontend expects.

5. Define API Routes:

In your routes/api.php file:

use App\Http\Controllers\PostController;

Route::get('/posts', [PostController::class, 'index'])->name('api.posts.index');

6. Frontend Implementation (JavaScript):

On your frontend (e.g., in a Blade view or a separate JavaScript file), you'll use the DataTable JavaScript library to make the AJAX request and render the table.

Here's a simplified example using jQuery and DataTables.js:

<!-- In your posts/index.blade.php -->
@push('styles')
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.3/css/jquery.dataTables.min.css">
@endpush

@push('scripts')
    <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
    <script>
        $(function() {
            $('#posts-table').DataTable({
                processing: true,
                serverSide: true,
                ajax: "{{ route('api.posts.index') }}", // Your API route
                columns: [
                    { data: 'DT_RowIndex', name: 'DT_RowIndex' }, // For the index column
                    { data: 'title', name: 'title' },
                    { data: 'body', name: 'body' },
                    { data: 'created_at', name: 'created_at' },
                    // Add columns for other fields from your resource
                ]
            });
        });
    </script>
@endpush

<table id="posts-table" class="table">
    <thead>
        <tr>
            <th>#</th>
            <th>Title</th>
            <th>Body</th>
            <th>Created At</th>
            <!-- Add headers for other columns -->
        </tr>
    </thead>
    <tbody>
        {{-- Data will be loaded by DataTable.js --}}
    </tbody>
</table>

Key Advantages of Yajra DataTable:

  • Server-side Processing: It handles pagination, sorting, and searching on the server-side, which is crucial for large datasets.
  • AJAX Integration: Seamlessly integrates with AJAX to fetch data without full page reloads.
  • Customization: Offers a wide range of options for customization, including column definitions, filtering, searching, and more.
  • Eloquent Integration: Works beautifully with Laravel's Eloquent ORM.

Alternative Libraries:

While Yajra DataTable is a dominant player, there might be other JavaScript-based solutions that can consume a Laravel API, such as:

  • Vue-Good-Table: If you're using Vue.js.
  • React-Table: If you're using React.
  • Vanilla JavaScript DataTable implementations: You can find many pure JavaScript DataTables libraries that you can configure to fetch data from your Laravel API.

However, for a direct Laravel-centric solution that integrates deeply with your backend, Yajra DataTable is generally the go-to library and precisely what you're looking for.

So, yes, it's very possible and libraries like Yajra DataTable automate a large part of this process for you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment