PHP code example of acunsoft / datatable-laravel

1. Go to this page and download the library: Download acunsoft/datatable-laravel 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/ */

    

acunsoft / datatable-laravel example snippets


use Acunsoft\DataTable\Laravel\Column;
use Acunsoft\DataTable\Laravel\TableResponse;

Route::get('/orders/data', function () {
    Gate::authorize('viewAny', Order::class);      // authorize every request

    return TableResponse::for(Order::query())
        ->columns([
            Column::make('customer')->sortable()->filterable()->searchUsing('customer_search'),
            Column::make('total')->type('decimal')->sortable()->filterable(),
            Column::make('created')->column('created_at')->type('datetime')->sortable()->filterable(),
        ])
        ->maxPageSize(100);
});

use Acunsoft\DataTable\Laravel\Column;
use Acunsoft\DataTable\Laravel\Livewire\WithDataTable;
use Illuminate\Database\Eloquent\Builder;
use Livewire\Component;

final class OrdersTable extends Component
{
    use WithDataTable;

    protected function columns(): array
    {
        return [
            Column::make('customer')->header('Müşteri')->sortable()->filterable()->searchUsing('customer_search'),
            Column::make('total')->header('Tutar')->type('decimal')->sortable()->filterable()
                ->format(fn ($value) => number_format((float) $value, 2, ',', '.').' ₺'),
            Column::make('created')->column('created_at')->header('Tarih')->type('datetime')->sortable(),
        ];
    }

    protected function query(): Builder
    {
        return Order::query()->whereBelongsTo(auth()->user()->team); // the rows this user may see
    }

    protected function selectable(): bool { return true; }       // optional
}

Column::make('customer')->hideable(false),   // always shown
Column::make('note')->hidden(),               // hidden until the user shows it

use Acunsoft\DataTable\Laravel\Action;

protected function rowActions(): array
{
    return [
        Action::make('edit')->label('Düzenle')
            ->handle(fn (Order $order) => $this->redirectRoute('orders.edit', $order)),
        Action::make('delete')->label('Sil')->confirm('Bu sipariş silinsin mi?')
            ->visible(fn (Order $order) => auth()->user()->can('delete', $order))
            ->handle(function (Order $order) {
                $this->authorize('delete', $order);
                $order->delete();
            }),
    ];
}

protected function bulkActions(): array
{
    return [
        Action::make('archive')->label('Arşivle')->confirm('Seçili siparişler arşivlensin mi?')
            ->handle(fn (Builder $selected) => $selected->update(['status' => 'archived'])),
    ];
}

protected function tableLayout(): array
{
    return [
        'topStart' => ['pageSize', 'search', 'orders.filters'], // your own Blade view
        'bottomEnd' => ['paging'],
        'bottomStart' => [],                                     // empty
    ];
}

protected function pagingOptions(): array
{
    return ['siblings' => 2, 'boundaries' => 1, 'firstLast' => true]; // « ‹ 1 … 3 4 5 6 7 … 200 › »
}

Column::make('total')->header('Tutar')->type('decimal')->filter(),
Column::make('status')->header('Durum')->options(['paid' => 'Ödendi', 'new' => 'Yeni']),

protected function filterPanel(): string { return 'drawer'; } // dropdown | drawer | modal

// Or your own component in place of the built-in button:
protected function tableLayout(): array { return ['topEnd' => ['orders.filter-modal', 'columns', 'tools']]; }

protected function toolbarButtons(): array
{
    return [
        'filters' => ['label' => 'Süz', 'class' => 'btn btn-outline-secondary'],
        'columns' => ['iconOnly' => true],
    ];
}

protected function pageSizeOptions(): array { return [10, 20, 50]; }
protected function defaultPageSize(): int { return 20; }

protected function responsive(): string { return 'collapse'; } // cards (default), scroll, collapse, modal, auto
protected function tableSize(): string { return 'sm'; }         // sm, md (default), lg

protected function columns(): array
{
    return [
        Column::make('customer')->header('Müşteri'),              // first column: always shown
        Column::make('total')->header('Tutar')->priority(1),      // stays on phones too
        Column::make('email')->header('E-posta')->priority(3),    // hides below 960px already
        Column::make('city')->header('Şehir'),                    // default 2: hides below 640px
    ];
}

protected function texts(): array
{
    return [
        'page_info' => __('Toplam: :total personel üyesinin :from ile :to arasını gösteriyor'),
        'search_placeholder' => __('Personel ara…'),
    ];
}

Column::make('city')->header('Şehir')->editable(['mal')->editable('min:0'),
Column::make('status')->header('Durum')->options(['new' => 'Yeni', 'paid' => 'Ödendi'])->editable(),

protected function resizableColumns(): bool { return true; }  // drag a header's edge, ←/→ on it
protected function reorderableColumns(): bool { return true; } // drag headers; ↑/↓ in the column menu

protected function fixedColumns(): array
{
    return ['start' => 1, 'end' => 1]; // first data column (with the checkbox) and the actions
}

use Livewire\Attributes\Lazy;

#[Lazy]
final class OrdersTable extends Component { use WithDataTable; /* … */ }

protected function detailView(): ?string
{
    return 'orders.lines'; // rendered with $row and $key
}

Column::make('total')->type('decimal')->sum(),          // or ->aggregate('avg' | 'min' | 'max' | 'count')

protected function exportFormats(): array { return ['xlsx', 'csv']; }  // shows them in the tools menu
protected function exportFilename(): string { return 'siparisler'; }
protected function printable(): bool { return true; }                  // adds "Print"

protected function queuedExports(): bool { return true; }          // past exportLimit(): prepared in the queue
protected function queuedExportLimit(): int { return 1_000_000; }  // the most a queued export writes
protected function exportDisk(): string { return 'local'; }        // where the file waits

protected function bulkActions(): array
{
    return [Action::make('archive')->label('Arşivle')->queued()->handle(fn ($selected) => $selected->update(['archived' => true]))];
}

use Acunsoft\DataTable\Laravel\Livewire\WithTableImport;

final class OrdersTable extends Component
{
    use WithDataTable, WithTableImport;

    protected function importOptions(): array
    {
        return ['

// migration: $table->string('customer_search')->index();
// model:
protected static function booted(): void
{
    static::saving(fn (Order $order) => $order->customer_search = Text::fold($order->customer));
}
// column:
Column::make('customer')->sortable()->filterable()->searchUsing('customer_search');

   // migration (PostgreSQL)
   $table->string('customer_search');
   DB::statement('CREATE EXTENSION IF NOT EXISTS pg_trgm');
   DB::statement('CREATE INDEX orders_customer_trgm ON orders USING gin (customer_search gin_trgm_ops)');

   // model
   use Acunsoft\DataTable\Laravel\Concerns\FoldsSearchColumns;

   protected function foldedSearchColumns(): array
   {
       return ['customer' => 'customer_search', 'city' => 'city_search'];
   }

   // column
   Column::make('customer')->sortable()->filterable()->searchUsing('customer_search'),
   

   // Livewire
   protected function searchEngine(string $search): ?iterable
   {
       return Order::search($search)->take(10_000)->keys();
   }

   // JSON endpoint
   TableResponse::for(Order::query())->columns([...])
       ->searchEngine(fn (string $search) => Order::search($search)->take(10_000)->keys());
   

Route::get('/orders/export', function (Request $request) {
    Gate::authorize('viewAny', Order::class);

    return TableExport::for(Order::query())
        ->columns($columns)
        ->query(TableQuery::fromRequest($request))  // the user's filters, search, sorting
        ->limit(50_000)
        ->xlsx('siparisler.xlsx');                  // or ->csv('siparisler.csv', ';')
});

use Acunsoft\DataTable\Laravel\Column;
use Acunsoft\DataTable\Laravel\Import\{ImportContext, TableImport};

final class OrdersImport extends TableImport
{
    protected function columns(): array
    {
        return [
            Column::make('email')->header('E-posta'),
            Column::make('customer')->header('Müşteri'),
            Column::make('total')->header('Tutar')->type('decimal'),
        ];
    }

    public function authorize(Request $request): bool { return $request->user()?->can('import', Order::class) ?? false; }
    protected function 

protected function importEndpoint(): ?string { return url('orders/import'); }

$sheet  = (new SheetReader(maxRows: 5_000))->read($file->getRealPath(), $file->getClientOriginalExtension());
$result = (new RowImporter($columns, => 'abc', 'message' => '…'], …]

$sheet = (new SheetReader(maxRows: 1_000_000))->stream($path, 'csv');
$sheet->headers;                      // ['Customer', 'Total']
foreach ($sheet->chunks(1_000) as $rows) { /* up to 1,000 rows, each as wide as the headers */ }

$query = TableQuery::fromRequest($request, maxPageSize: 100);   // or fromArray([...])
$page  = QueryApplier::paginate(Order::query(), $query, $columns); // LengthAwarePaginator
blade
{{-- resources/views/orders/lines.blade.php --}}
<ul>
    @foreach ($row->lines as $line)
        <li>{{ $line->product }} × {{ $line->quantity }}</li>
    @endforeach
</ul>
bash
php artisan vendor:publish --tag=acun-datatable-views