Skip to content

Instantly share code, notes, and snippets.

@extralam
Last active March 26, 2019 09:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save extralam/8266f459e44d6e0c1bcf059e5f09b809 to your computer and use it in GitHub Desktop.
Save extralam/8266f459e44d6e0c1bcf059e5f09b809 to your computer and use it in GitHub Desktop.
Base Grid Controller on Laravel-admin
<?php
namespace App\Admin\Controllers\Lam;
use App\Models\ApiLog;
class ApiLogController extends BaseGridController
{
public function __construct()
{
$this->name = 'ApiLog';
$this->clazz = new ApiLog();
}
}
<?
namespace App\Admin\Controllers\Lam;
use App\Admin\Controllers\BaseController;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Schema;
class BaseGridController extends BaseController
{
protected $name;
protected $clazz;
/**
* Index interface.
*
* @param Content $content
* @return Content
*/
public function index(Content $content)
{
return $content
->header($this->name . '列表')
->description($this->name . '列表')
->body($this->grid());
}
private function getAllFields($baseModel){
if($columns = Cache::get('fields_'.$this->name)){
}else{
$columns = Schema::getColumnListing($baseModel->getTable());
Cache::put('fields_'.$this->name , $columns , 5);
}
return $columns;
}
/**
* Make a grid builder.
*
* @return Grid
*/
protected function grid()
{
$grid = new Grid($this->clazz);
foreach ($this->getAllFields($this->clazz) as $field){
if(strtolower(substr($field, -2)) === 'at'){
$grid->{$field}()->display(function($d){
if(is_numeric($d)) {
return getDateTimeFormat($d, 'Y-m-d H:m:s');
}else{
return $d;
}
});
}else {
$grid->{$field}();
}
}
$grid->paginate(24);
$grid->perPages([24, 36, 48]);
$grid->disableActions();
$grid->disableCreateButton();
$grid->disableRowSelector();
$grid->disableExport();
$this->filter($grid);
$grid->model()->orderBy('id','DESC');
return $grid;
}
protected function filter(&$grid){
$grid->filter(function ($filter){
foreach ($this->getAllFields($this->clazz) as $field){
$filter->like($field , $field);
}
$filter->between('created_at', '建立日期')->datetime();
$filter->between('updated_at', '修改日期')->datetime();
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment