Skip to content
Icon

WARNING You're browsing the documentation for an upcoming version of Laravel DataTables. The documentation and features of this release are subject to change.

Column Formatting

DataTables supports formatting columns using formatter classes through the formatColumn() API. This allows you to define reusable formatters for consistent column presentation.


Creating a Formatter

Create a class that implements the Yajra\DataTables\Contracts\Formatter interface:

<?php
 
namespace App\DataTables\Formatters;
 
use App\Models\User;
use Yajra\DataTables\Contracts\Formatter;
 
class StatusFormatter implements Formatter
{
public function format(mixed $value, User $row): string
{
return match ($value) {
'active' => '<span class="badge bg-success">Active</span>',
'inactive' => '<span class="badge bg-secondary">Inactive</span>',
'pending' => '<span class="badge bg-warning">Pending</span>',
default => '<span class="badge bg-dark">' . e($value) . '</span>',
};
}
}

Basic Usage

use Yajra\DataTables\Facades\DataTables;
use App\Models\User;
use App\DataTables\Formatters\StatusFormatter;
 
Route::get('user-data', function() {
return DataTables::eloquent(User::query())
->formatColumn('status', new StatusFormatter())
->toJson();
});

Format Multiple Columns

use Yajra\DataTables\Facades\DataTables;
use App\Models\User;
use App\DataTables\Formatters\DateFormatter;
 
Route::get('user-data', function() {
return DataTables::eloquent(User::query())
->formatColumn(['created_at', 'updated_at'], new DateFormatter('M d, Y'))
->toJson();
});

Using Closures

For simple formatting, use closures instead of a formatter class:

use Yajra\DataTables\Facades\DataTables;
use App\Models\User;
 
Route::get('user-data', function() {
return DataTables::eloquent(User::query())
->formatColumn('status', function (mixed $value, User $row) {
return ucfirst($value);
})
->toJson();
});
 
---
 
<a name="query-builder-closure"></a>
### Query Builder / Collection
 
For Query Builder or Collection data sources, use `object` type for `$row`:
 
```php
use Illuminate\Support\Facades\DB;
use Yajra\DataTables\Facades\DataTables;
 
Route::get('user-data', function() {
return DataTables::query(DB::table('users'))
->formatColumn('status', function (mixed $value, object $row) {
return ucfirst($value);
})
->toJson();
});

Accessor Format

If no formatter or closure is provided, the column value is automatically extracted:

use Yajra\DataTables\Facades\DataTables;
use App\Models\User;
 
Route::get('user-data', function() {
return DataTables::eloquent(User::query())
// Extracts and displays the 'name' attribute
->formatColumn('name', 'name')
->toJson();
});

See Also