PHP code example of humweb / inertia-table

1. Go to this page and download the library: Download humweb/inertia-table library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

humweb / inertia-table example snippets


use Humweb\Table\Resource;
use Humweb\Table\Fields\{FieldCollection, ID, Text, Badge};
use Humweb\Table\Filters\{FilterCollection, SelectFilter, TextFilter};

class UserResource extends Resource
{
    protected string $model = User::class;
    public string|Sort $defaultSort = 'name';
    protected array $with = ['team'];

    public function fields(): FieldCollection
    {
        return FieldCollection::make([
            ID::make('ID')->sortable(),
            Text::make('Name')->sortable()->searchable(),
            Text::make('Email')->sortable()->searchable(),
            Badge::make('Status')->sortable()->withMeta([
                'map' => [
                    'active' => ['label' => 'Active', 'class' => 'badge-green'],
                    'inactive' => ['label' => 'Inactive', 'class' => 'badge-gray'],
                ],
            ]),
        ]);
    }

    public function filters(): FilterCollection
    {
        return FilterCollection::make([
            SelectFilter::make('status', 'Status', [
                'active' => 'Active',
                'inactive' => 'Inactive',
            ]),
            TextFilter::make('name', 'Name'),
        ]);
    }
}

use Inertia\Inertia;

class UserController extends Controller
{
    public function index(Request $request)
    {
        return Inertia::render('Users/Index')
            ->table(fn (InertiaTable $table) =>
                UserResource::make($request)->toResponse($table)
            );
    }
}

public function index(Request $request)
{
    return Inertia::render('Staff/Teams/Show', [
        'team' => $team,
    ])
        ->table('members', fn (InertiaTable $table) =>
            MemberResource::make($request)->toResponse($table)
        )
        ->table('invitations', fn (InertiaTable $table) =>
            InvitationResource::make($request)->toResponse($table)
        );
}

$resource->addParameter('team_id', $team->id);

// In resource:
public function filterTeamId($value): void
{
    $this->query->where('team_id', $value);
}

public function globalFilter($query, $value): void
{
    $query->where(function ($q) use ($value) {
        $q->where('name', 'ilike', "%{$value}%")
          ->orWhere('email', 'ilike', "%{$value}%");
    });
}

$resource->runtimeTransform(function ($record) {
    $record['full_name'] = $record['first_name'] . ' ' . $record['last_name'];
    return $record;
});

Text::make('Name')
    ->sortable()                          // Enable server-side sorting (BasicSort)
    ->sortable(new PowerJoinSort('team', 'name'))  // Sort via relation
    ->sortable(new AggregateSort('posts', 'count')) // Sort by withCount
    ->sortableOnClient()                  // Client-side sort (no server round-trip)
    ->sortField('name_lower')             // Sort on a different column than display
    ->searchable()                        // Include in column search
    ->visible(false)                      // Hidden by default
    ->visibility(true)                    // Allow toggling visibility
    ->nullable()                          // Mark as nullable
    ->withMeta(['tooltip' => 'Full name'])    // Arbitrary metadata sent to frontend

TextFilter::make('name', 'Name')
    ->exact()                 // Exact match instead of LIKE
    ->startsWith()            // LIKE 'value%'
    ->endsWith()              // LIKE '%value'
    ->fullSearch()            // LIKE '%value%' (default)
    ->relation('team', 'name') // Filter within a relationship
    ->rules('string|max:100') // Validation rules

Text::make('Score')
    ->sortable(new BasicCollectionSort(SortType::Integer), SortMode::Collection)

protected function pipeline(QueryPipeline $pipeline): QueryPipeline
{
    // Add a custom stage before sorting
    $pipeline->before(ApplySorts::class, new MyCustomStage());

    // Replace the default global search
    $pipeline->replace(ApplyGlobalSearch::class, new MyGlobalSearch());

    // Add a stage after filters
    $pipeline->after(ApplyFilters::class, new ApplyTenantScope($this->tenantId));

    return $pipeline;
}

use Humweb\Table\Pipeline\QueryStage;
use Humweb\Table\TableRequest;
use Illuminate\Database\Eloquent\Builder;

class ApplyTenantScope implements QueryStage
{
    public function __construct(private int $tenantId) {}

    public function handle(Builder $query, TableRequest $request, Closure $next): Builder
    {
        $query->where('tenant_id', $this->tenantId);

        return $next($query);
    }
}

$tableRequest = new TableRequest($request, 'members');
$tableRequest->getSortParam();    // reads ?members.sort=
$tableRequest->getSearchParams(); // reads ?members.search[...]=
$tableRequest->getFilterParams(); // reads ?members.filters[...]=
$tableRequest->getPage();         // reads ?members.page=
$tableRequest->getPerPage();      // reads ?members.perPage=

// Single table (key = 'default', prop = 'table')
->table(fn (InertiaTable $table) => ...)

// Named table (prop = 'tables.{key}')
->table('members', fn (InertiaTable $table) => ...)
->table('invitations', fn (InertiaTable $table) => ...)

// config/inertia-table.php
return [
    'pagination' => [
        'max_per_page' => 100,
        'default_per_page' => 15,
    ],
];
bash
php artisan vendor:publish --tag="inertia-table-config"