PHP code example of mediconesystems / livewire-datatables

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

    

mediconesystems / livewire-datatables example snippets

 artisan make:livewire-datatable foo
 artisan make:livewire-datatable tables.bar
 artisan make:livewire-datatable users-table --model=user

class ComplexDemoTable extends LivewireDatatable
{

    public function builder()
    {
        return User::query();
    }

    public function columns()
    {
        return [
            NumberColumn::name('id')
                ->label('ID')
                ->linkTo('job', 6),

            BooleanColumn::name('email_verified_at')
                ->label('Email Verified')
                ->format()
                ->filterable(),

            Column::name('name')
                ->defaultSort('asc')
                ->group('group1')
                ->searchable()
                ->hideable()
                ->filterable(),

            Column::name('planet.name')
                ->label('Planet')
                ->group('group1')
                ->searchable()
                ->hideable()
                ->filterable($this->planets),

            // Column that counts every line from 1 upwards, independent of content
            Column::index($this);

            DateColumn::name('dob')
                ->label('DOB')
                ->group('group2')
                ->filterable()
                ->hide(),

            (new LabelColumn())
                ->label('My custom heading')
                ->content('This fixed string appears in every row'),

            NumberColumn::name('dollars_spent')
                ->enableSummary(),
        ];
    }
}

NumberColumn::name('students.age:sum')->label('Student Sum'),

NumberColumn::name('students.age:avg')->label('Student Avg'),

NumberColumn::name('students.age:min')->label('Student Min'),

NumberColumn::name('students.age:max')->label('Student Max'),

class GroupDemoTable extends LivewireDatatable
{
    public $groupLabels = [
         'group1' => 'app.translation_for_group_1'
         'group2' => 'app.translation_for_group_2'
    ];

public function columns()
{
    return [
        Column::name('planets.name')
            ->group('group1')
            ->label('Planet'),

        Column::name('planets.name')
            ->group('group2')
            ->label('Planet'),

public function columns()
{
    return [
        Column::name('dollars_spent')
            ->label('Expenses in Dollar')
            ->enableSummary(),

        Column::name('euro_spent')
            ->label('Expenses in Euro')
            ->enableSummary(),

public function buildActions()
    {
        return [

            Action::value('edit')->label('Edit Selected')->group('Default Options')->callback(function ($mode, $items) {
                // $items contains an array with the primary keys of the selected items
            }),

            Action::value('update')->label('Update Selected')->group('Default Options')->callback(function ($mode, $items) {
                // $items contains an array with the primary keys of the selected items
            }),

            Action::groupBy('Export Options', function () {
                return [
                    Action::value('csv')->label('Export CSV')->export('SalesOrders.csv'),
                    Action::value('html')->label('Export HTML')->export('SalesOrders.html'),
                    Action::value('xlsx')->label('Export XLSX')->export('SalesOrders.xlsx')->styles($this->exportStyles)->widths($this->exportWidths)
                ];
            }),
        ];
    }

public function getExportStylesProperty()
    {
        return [
            '1'  => ['font' => ['bold' => true]],
            'B2' => ['font' => ['italic' => true]],
            'C'  => ['font' => ['size' => 16]],
        ];
    }

    public function getExportWidthsProperty()
    {
        return [
            'A' => 55,
            'B' => 45,
        ];
    }

use Mediconesystems\LivewireDatatables\Traits\CanPinRecords;

class RecordTable extends LivewireDatatable
{
    use CanPinRecords;

    public $model = Record::class;

    public function columns()
    {
        return [
            Column::checkbox(),

            // ...



public function builder()
{
    return User::query()
        ->leftJoin('planets', 'planets.id', 'users.planet_id')
        ->leftJoin('moons', 'moons.id', 'planets.moon_id')
        ->groupBy('users.id');
}

public function columns()
{
    return [
        NumberColumn::name('id')
            ->filterable(),

        Column::name('planets.name')
            ->label('Planet'),

        Column::raw('GROUP_CONCAT(planets.name SEPARATOR " | ") AS `Moon`'),

        ...
}


class CallbackDemoTable extends LivewireDatatable
{
    public model = User::class

    public function columns()
    {
        return [
            Column::name('users.id'),

            Column::name('users.dob')->format(),

            Column::callback(['dob', 'signup_date'], function ($dob, $signupDate) {
                $age = $signupDate->diffInYears($dob);
                return $age > 18
                    ? '<span class="text-red-500">' . $age . '</span>'
                    : $age;
            })->exportCallback(function ($dob, $signupDate), {
                return $age = $signupDate->diffInYears($dob);
            }),

            ...
    }
}

class CallbackDemoTable extends LivewireDatatable
{
    public $defaultFilters = [
        'deleted_at' => '0',
    ];

    public function builder()
    {
        return User::query()->withTrashed();
    }

    public function columns()
    {
        return [
            Column::name('id'),
            BooleanColumn::name('deleted_at')->filterable(),
        ];
    }
}

class CallbackDemoTable extends LivewireDatatable
{
    public model = User::class

    public function columns()
    {
        return [
            Column::name('users.id'),

            Column::name('users.dob')->view('tables.dateview'),

            Column::name('users.signup_date')->format(),
        ];
    }

class EditableTable extends LivewireDatatable
{

    public $model = User::class;

    public function columns()
    {
        return [
            Column::name('id')
                ->label('ID')
                ->linkTo('job', 6),

            Column::name('email')
                ->editable(),

            ...
        ];
    }
}

public function getPersistKeyProperty()
{
    return Auth::id() . '-' . parent::getPersistKeyProperty();
}

/* Migration */

class CreateComplexQueriesTable extends Migration
{
    public function up()
    {
        Schema::create('complex_queries', function (Blueprint $table) {
            $table->id();
            $table->unsignedInteger('user_id');
            $table->string('table');
            $table->json('rules');
            $table->string('name');
            $table->timestamps();
        });
    }
}


/* Model */

class ComplexQuery extends BaseModel
{
    protected $casts = ['rules' => 'array'];

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

/* Datatable Class */

class TableWithSaving extends LivewireDatatable
{
    ...

    public function saveQuery($name, $rules)
    {
        Auth::user()->complex_queries()->create([
            'table' => $this->name,
            'name' => $name,
            'rules' => $rules
        ]);

        $this->emit('updateSavedQueries', $this->getSavedQueries());
    }

    public function deleteQuery($id)
    {
        ComplexQuery::destroy($id);

        $this->emit('updateSavedQueries', $this->getSavedQueries());
    }

    public function getSavedQueries()
    {
        return Auth::user()->complex_queries()->where('table', $this->name)->get();
    }

    ...
}

public function rowClasses($row, $loop)
{
    return 'divide-x divide-gray-100 text-sm text-gray-900 ' . ($this->rowIsSelected($row) ? 'bg-yellow-100' : ($row->{'car.model'} === 'Ferrari' ? 'bg-red-500' : ($loop->even ? 'bg-gray-100' : 'bg-gray-50')));
}

public function cellClasses($row, $column)
{
    return 'text-sm ' . ($this->rowIsSelected($row) ? ' text-gray-900' : ($row->{'car.model'} === 'Ferrari' ? ' text-white' : ' text-gray-900'));
}
bash
php artisan vendor:publish --provider="Mediconesystems\LivewireDatatables\LivewireDatatablesServiceProvider"
$this->model::destroy($primaryKey)
OR
Column::callback(['name', 'allegiance'], function ($name, $allegiance) { return "$name is allied to $allegiance"; })->filterable(['Rebellion', 'Empire'])->filterOn('users.allegiance')
$value
$row
public function deleteQuery(Int $id)
$row
$row
livewire-datatables.php