PHP code example of camohub / laravel-datagrid

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

    

camohub / laravel-datagrid example snippets


public function getArticlesDatagrid()
{
    $grid = new Datagrid(Article::with('user'));

    $grid->addColumn('id')
        ->setSort();

    $grid->addColumn('title')
        ->setSort()
        ->setFilter(function($model, $value) {
            return $value ? $model->where('title', 'like', "%$value%") : $model;
        });

    $grid->addColumn('created_at', 'Created')
        // Needs valid js regexp pattern.
        ->setJSFilterPattern('\d{2}\.\d{2}\.\d{4} \d{2}:\d{2}')
        ->setRender(function($value, $item) {
            return '<b>' . $value->format('d.m.Y H:i') . '</b>';
        })
        // Turns off template html escaping.
        ->setNoEscape()
        ->setSort();

    $grid->addColumn('visible', 'Visible')
        ->setOutherClass(function($value, $row) {
            return $value ? 'bg-primary text-center' : 'bg-danger text-center';
        })
        ->setSelectFilter([0 => 'hidden', 1 => 'active'], 'all')
        ->setFilter(function ($model, $value) {
            return $model->where('visible', $value);
        });

    // HasOne relation
    $grid->addColumn('user.name', 'User');

    // ManyHasMany relation
    $grid->addColumn('user.roles', 'Roles')
        ->setRender(function($value, $item) {
            return $value->map( function($value) { return $value->name; } )->join(', ');
        });

    // TYPE_CUSTOM intended for content not related to model.
    $grid->addColumn('', '', Column::TYPE_CUSTOM)
        ->setNoEscape()
        ->setRender(function($value, $item) {
            return '
                <a href="' . route('admin.articles.edit', ['id' => $item->id]) . '">edit</a>
                <a href="' . route('admin.articles.visibility', ['id' => $item->id]) . '">visibility</a>
                <a href="' . route('admin.articles.delete', ['id' => $item->id]) . '" class="text-danger">delete</a>
            ';
        });

    return $grid;
}