PHP code example of hasanalyazidi / laravel-datatables
1. Go to this page and download the library: Download hasanalyazidi/laravel-datatables 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/ */
hasanalyazidi / laravel-datatables example snippets
// 1. One class
class UsersDataTable extends DataTable
{
public function columns(): array
{
return [
Column::id(),
Column::make('name'),
Column::createdAt(),
];
}
protected function query(): Builder
{
return User::query();
}
}
// 2. One route line
Route::dataTable('users/data', UsersDataTable::class)->name('users.data');
namespace App\DataTables;
use App\Models\User;
use HasanAlyazidi\DataTables\Badge;
use HasanAlyazidi\DataTables\Column;
use HasanAlyazidi\DataTables\ColumnOrder;
use HasanAlyazidi\DataTables\DataTable;
use Illuminate\Database\Eloquent\Builder;
class UsersDataTable extends DataTable
{
public function columns(): array
{
return [
Column::id('users.id'),
Column::make('name'),
Column::make('email')->default('-'),
Column::badge('status', [
1 => [Badge::SUCCESS, __('Active')],
0 => [Badge::DANGER, __('Blocked')],
]),
Column::createdAt(),
Column::actions()->render(function (User $user) {
return view('users.actions', ['user' => $user])->render();
}),
];
}
public function title(): string
{
return __('Users'); // used as the Excel sheet name and PDF heading
}
protected function query(): Builder
{
// Put your access rules here. The table shows ONLY what this returns.
return User::query();
}
protected function defaultOrder(): array
{
return [ColumnOrder::desc('created_at')];
}
}
use HasanAlyazidi\DataTables\DataTable;
use HasanAlyazidi\DataTables\LocalizedSearch;
// Translations in a joined table (alias "fb_trans"):
DataTable::localizeSearchUsing(LocalizedSearch::join('fb_trans'));
// Or several joins (current language + fallback):
DataTable::localizeSearchUsing(LocalizedSearch::join('trans', 'fb_trans'));
// Or columns like name_ar / name_en:
DataTable::localizeSearchUsing(LocalizedSearch::suffix('ar', 'en'));
// Or follow the current app language (name_ar when the app is in Arabic):
DataTable::localizeSearchUsing(LocalizedSearch::suffix());
// Or anything else:
DataTable::localizeSearchUsing(function (string $column) {
return ['anything.'.$column];
});
Column::make('name')->searchLocalized(),
// One table that stores translations differently — override in that class:
protected function localizedSearchColumns(string $column): array
{
return ['pt.'.$column];
}
// One column that needs exact columns — name them and skip the magic:
Column::make('name')->searchColumns(['name_ar', 'name_en']),
protected $exporters = ['csv', 'pdf']; // or [] to turn exports off for this table