【PHP 后台框架】基于Laravel的Dcat Admin框架使用记录

Dcat Admin

Dcat Admin是一个基于laravel-admin二次开发而成的后台系统构建工具,只需极少的代码即可快速构建出一个功能完善的高颜值后台系统。支持页面一键生成CURD代码,内置丰富的后台常用组件,开箱即用,让开发者告别冗杂的HTML代码,对后端开发者非常友好。

记录

文件上传下载

  • 修改 Config 目录下 admin.php文件
'upload' => [
    // Disk in `config/filesystem.php`.
    'disk' => 'admin',
    // Image and file upload path under the disk above.
    'directory' => [
        'image' => 'images',
        'file'  => 'files',
    ],
],

  • Filesystems.php 文件
'disks' => [
    'admin' => [
        'driver' => 'local',
        'root' => public_path('uploads'),
        'visibility' => 'public',
        'url' => env('APP_URL').'/uploads',
    ],
],
  • 修改 .env 文件
APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:ApdWBVhTPxwnoM59rhazb4/XiN4OSL7lkMGQDFxmie0=
APP_DEBUG=true //正式环境 禁用开发工具 改成false
APP_URL=http://localhost:8090    //文件不显示 注意端口号

多语言配置

多语言目录文件:D:\GitHub\EUREKA-EMS\resources\lang\zh-CN

安装:composer require "overtrue/laravel-lang:~3.0"
完成上面的操作后,将项目文件 config/app.php 中的下一行
Illuminate\Translation\TranslationServiceProvider::class,
替换为:
Overtrue\LaravelLang\TranslationServiceProvider::class,
如果你想修改扩展包提供的语言文件,可以使用以下命令发布语言文件到项目里:
php artisan lang:publish zh-CN

Pjax刷新页面

Admin::script(
<<<JS
    // 3秒后刷新当前页面
    setTimeout(function () {
        Dcat.reload();
    }, 3000);
JS
);

权限控制

只查询和当前登录用户有关联的数据

$grid->model()->where('que_create_byid',Admin::user()->id);

if (Admin::user()->isRole('administrator')) {
	...                   
} 

管理员用户数据

文件在 vendor\dcat\laravel-admin\src\Controllers\UserController.php

多后台

  • 生成新应用
php artisan admin:app NewAdmin
  • 启用

开配置文件config/admin.php,加入以下代码

return [
    ...
    'multi_app' => [
        // 与新应用的配置文件名称一致
        // 设置为true启用,false则是停用
        'new-admin' => true,
    ],
];

浏览器访问这个新应用了http://localhost:8000/new-admin

  • 更改菜单

执行sql脚本

/*
 Navicat Premium Data Transfer

 Source Server         : mysql
 Source Server Type    : MySQL
 Source Server Version : 50726
 Source Host           : localhost:3306
 Source Schema         : nfdw_ems

 Target Server Type    : MySQL
 Target Server Version : 50726
 File Encoding         : 65001

 Date: 29/07/2020 16:14:00
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for nfdw_ems_i1_permission_menu
-- ----------------------------
DROP TABLE IF EXISTS `nfdw_ems_i1_permission_menu`;
CREATE TABLE `nfdw_ems_i1_permission_menu`  (
  `permission_id` int(11) NOT NULL,
  `menu_id` int(11) NOT NULL,
  `created_at` timestamp(0) NULL DEFAULT NULL,
  `updated_at` timestamp(0) NULL DEFAULT NULL,
  UNIQUE INDEX `admin_permission_menu_permission_id_menu_id_index`(`permission_id`, `menu_id`) USING BTREE
) ENGINE = MyISAM CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci ROW_FORMAT = Fixed;

-- ----------------------------
-- Records of nfdw_ems_i1_permission_menu
-- ----------------------------
INSERT INTO `nfdw_ems_i1_permission_menu` VALUES (8, 9, NULL, NULL);
INSERT INTO `nfdw_ems_i1_permission_menu` VALUES (9, 9, NULL, NULL);
INSERT INTO `nfdw_ems_i1_permission_menu` VALUES (10, 9, NULL, NULL);
INSERT INTO `nfdw_ems_i1_permission_menu` VALUES (8, 10, NULL, NULL);
INSERT INTO `nfdw_ems_i1_permission_menu` VALUES (9, 10, NULL, NULL);
INSERT INTO `nfdw_ems_i1_permission_menu` VALUES (10, 10, NULL, NULL);
INSERT INTO `nfdw_ems_i1_permission_menu` VALUES (8, 12, NULL, NULL);
INSERT INTO `nfdw_ems_i1_permission_menu` VALUES (9, 12, NULL, NULL);
INSERT INTO `nfdw_ems_i1_permission_menu` VALUES (10, 12, NULL, NULL);
INSERT INTO `nfdw_ems_i1_permission_menu` VALUES (8, 11, NULL, NULL);
INSERT INTO `nfdw_ems_i1_permission_menu` VALUES (9, 11, NULL, NULL);
INSERT INTO `nfdw_ems_i1_permission_menu` VALUES (10, 11, NULL, NULL);
INSERT INTO `nfdw_ems_i1_permission_menu` VALUES (8, 13, NULL, NULL);
INSERT INTO `nfdw_ems_i1_permission_menu` VALUES (9, 13, NULL, NULL);
INSERT INTO `nfdw_ems_i1_permission_menu` VALUES (10, 13, NULL, NULL);

SET FOREIGN_KEY_CHECKS = 1;


/*
 Navicat Premium Data Transfer

 Source Server         : mysql
 Source Server Type    : MySQL
 Source Server Version : 50726
 Source Host           : localhost:3306
 Source Schema         : nfdw_ems

 Target Server Type    : MySQL
 Target Server Version : 50726
 File Encoding         : 65001

 Date: 29/07/2020 16:13:49
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for nfdw_ems_i1_menu
-- ----------------------------
DROP TABLE IF EXISTS `nfdw_ems_i1_menu`;
CREATE TABLE `nfdw_ems_i1_menu`  (
  `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `parent_id` int(11) NOT NULL DEFAULT 0,
  `order` int(11) NOT NULL DEFAULT 0,
  `title` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `icon` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL,
  `uri` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL,
  `created_at` timestamp(0) NULL DEFAULT NULL,
  `updated_at` timestamp(0) NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = MyISAM AUTO_INCREMENT = 8 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of nfdw_ems_i1_menu
-- ----------------------------
INSERT INTO `nfdw_ems_i1_menu` VALUES (5, 2, 5, 'Permission', '', 'auth/permissions', '2020-07-23 02:30:26', NULL);
INSERT INTO `nfdw_ems_i1_menu` VALUES (4, 2, 4, 'Roles', '', 'auth/roles', '2020-07-23 02:30:26', NULL);
INSERT INTO `nfdw_ems_i1_menu` VALUES (3, 2, 3, 'Users', '', 'auth/users', '2020-07-23 02:30:26', NULL);
INSERT INTO `nfdw_ems_i1_menu` VALUES (2, 0, 2, 'Admin', 'feather icon-settings', '', '2020-07-23 02:30:26', NULL);
INSERT INTO `nfdw_ems_i1_menu` VALUES (1, 0, 1, 'Index', 'feather icon-bar-chart-2', '/', '2020-07-23 02:30:26', NULL);
INSERT INTO `nfdw_ems_i1_menu` VALUES (6, 2, 6, 'Menu', '', 'auth/menu', '2020-07-23 02:30:26', NULL);
INSERT INTO `nfdw_ems_i1_menu` VALUES (7, 2, 7, 'Operation log', '', 'auth/logs', '2020-07-23 02:30:26', NULL);

SET FOREIGN_KEY_CHECKS = 1;


/*
 Navicat Premium Data Transfer

 Source Server         : mysql
 Source Server Type    : MySQL
 Source Server Version : 50726
 Source Host           : localhost:3306
 Source Schema         : nfdw_ems

 Target Server Type    : MySQL
 Target Server Version : 50726
 File Encoding         : 65001

 Date: 29/07/2020 16:13:43
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for nfdw_ems_i1_role_menu
-- ----------------------------
DROP TABLE IF EXISTS `nfdw_ems_i1_role_menu`;
CREATE TABLE `nfdw_ems_i1_role_menu`  (
  `role_id` bigint(20) NOT NULL,
  `menu_id` bigint(20) NOT NULL,
  `created_at` timestamp(0) NULL DEFAULT NULL,
  `updated_at` timestamp(0) NULL DEFAULT NULL,
  UNIQUE INDEX `admin_role_menu_role_id_menu_id_unique`(`role_id`, `menu_id`) USING BTREE
) ENGINE = MyISAM CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci ROW_FORMAT = Fixed;

-- ----------------------------
-- Records of nfdw_ems_i1_role_menu
-- ----------------------------
INSERT INTO `nfdw_ems_i1_role_menu` VALUES (1, 9, NULL, NULL);
INSERT INTO `nfdw_ems_i1_role_menu` VALUES (1, 10, NULL, NULL);
INSERT INTO `nfdw_ems_i1_role_menu` VALUES (1, 11, NULL, NULL);
INSERT INTO `nfdw_ems_i1_role_menu` VALUES (1, 12, NULL, NULL);
INSERT INTO `nfdw_ems_i1_role_menu` VALUES (2, 9, NULL, NULL);
INSERT INTO `nfdw_ems_i1_role_menu` VALUES (2, 10, NULL, NULL);
INSERT INTO `nfdw_ems_i1_role_menu` VALUES (2, 12, NULL, NULL);
INSERT INTO `nfdw_ems_i1_role_menu` VALUES (2, 11, NULL, NULL);
INSERT INTO `nfdw_ems_i1_role_menu` VALUES (1, 13, NULL, NULL);
INSERT INTO `nfdw_ems_i1_role_menu` VALUES (2, 13, NULL, NULL);

SET FOREIGN_KEY_CHECKS = 1;


/*
 Navicat Premium Data Transfer

 Source Server         : mysql
 Source Server Type    : MySQL
 Source Server Version : 50726
 Source Host           : localhost:3306
 Source Schema         : nfdw_ems

 Target Server Type    : MySQL
 Target Server Version : 50726
 File Encoding         : 65001

 Date: 29/07/2020 16:14:06
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for nfdw_ems_i1_role_permissions
-- ----------------------------
DROP TABLE IF EXISTS `nfdw_ems_i1_role_permissions`;
CREATE TABLE `nfdw_ems_i1_role_permissions`  (
  `role_id` int(11) NOT NULL,
  `permission_id` int(11) NOT NULL,
  `created_at` timestamp(0) NULL DEFAULT NULL,
  `updated_at` timestamp(0) NULL DEFAULT NULL,
  UNIQUE INDEX `admin_role_permissions_role_id_permission_id_index`(`role_id`, `permission_id`) USING BTREE
) ENGINE = MyISAM CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci ROW_FORMAT = Fixed;

-- ----------------------------
-- Records of nfdw_ems_i1_role_permissions
-- ----------------------------
INSERT INTO `nfdw_ems_i1_role_permissions` VALUES (2, 8, NULL, NULL);
INSERT INTO `nfdw_ems_i1_role_permissions` VALUES (2, 9, NULL, NULL);
INSERT INTO `nfdw_ems_i1_role_permissions` VALUES (2, 10, NULL, NULL);

SET FOREIGN_KEY_CHECKS = 1;

Excel导入

前期准备

  • 安装
composer require maatwebsite/excel
  • Maatwebsite\Excel\ExcelServiceProviderconfig/app.php以下位置添加ServiceProvider
'providers' => [
    /*
     * Package Service Providers...
     */
    Maatwebsite\Excel\ExcelServiceProvider::class,
]
  • 手动添加,config/app.php
'aliases' => [
    ...
    'Excel' => Maatwebsite\Excel\Facades\Excel::class,
]
  • 发布配置
php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider"

将创建一个新配置文件 config/excel.php

导入

  • 创建一个导入类 app/Imports
php artisan make:import QuestionImport --model= Question

├── app
│   ├── Imports
│   │   ├── QuestionImport.php
│ 
└── composer.json
<?php

namespace App\Imports;

use App\Models\TiKu\Question;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
class QuestionImport implements ToModel, WithHeadingRow
{
    /**
     * @param array $row
     *
     * @return \Illuminate\Database\Eloquent\Model|null
     */
    public function model(array $row)
    {
        return new Question([
            'id' => $row['id'],
            'questype_id' => $row['questype_id'],
            'que_index' => $row['que_index'],
            'que_create_byid' => $row['que_create_byid'],
            'que_create_byname' => $row['que_create_byname'],
            'que_last_byid' => $row['que_last_byid'],
            'que_last_byname' => $row['que_last_byname'],
            'que_select' => $row['que_select'],
            'que_selectnum' => $row['que_selectnum'],
            'que_answer' => $row['que_answer'],
            'que_describe' => $row['que_describe'],
            'que_status' => $row['que_status'],
            'que_level' => $row['que_level'],
            'que_sequence' => $row['que_sequence'],
            'declaration_id' => $row['declaration_id'],
            'major_id' => $row['major_id'],
            'created_at' => $row['created_at'],
            'updated_at' => $row['updated_at'],
        ]);
    }
}

{% note warning %}
注意:模型需要与QuestionImport 字段名一致
{% endnote %}

模型 Model

<?php

namespace App\Models\TiKu;
use Dcat\Admin\Traits\HasDateTimeFormatter;
use Illuminate\Database\Eloquent\Model;

class Question extends Model
{
    use HasDateTimeFormatter;
    //字段名
    protected $fillable = ['id', 'questype_id', 'que_index', 'que_create_byid', 'que_create_byname', 'que_last_byid', 'que_last_byname', 'que_select', 'que_selectnum', 'que_answer', 'que_describe', 'que_status', 'que_level', 'que_sequence', 'declaration_id', 'major_id', 'created_at', 'updated_at'];

    public function major()
    {
        return $this->belongsTo(Major::class);
    }

    public function declaration()
    {
        return $this->belongsTo(Declaration::class);
    }

    public function questype()
    {
        return $this->belongsTo(Questype::class);
    }
}

  • 生成工具表单
php artisan admin:form QuestionData

修改:

<?php

namespace App\Admin\Forms;

use App\Imports\QuestionImport;
use Dcat\Admin\Widgets\Form;
use Symfony\Component\HttpFoundation\Response;
use Maatwebsite\Excel\Facades\Excel;

class QuestionData extends Form
{
    // 增加一个自定义属性保存用户ID
    protected $id = 'DATA_IMPORT';

    // 构造方法的参数必须设置默认值
    public function __construct($id = null)
    {
        $this->id = $id;
        parent::__construct();
    }
    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return Response
     */
    public function handle(array $input)
    {
        // 下面的代码获取到上传的文件,然后使用`maatwebsite/excel`等包来处理上传你的文件,保存到数据库
        $file = $input['file'];
        if(!$file){
            return $this->error('请先上传文件');
        }
        // 导入
        Excel::import(new QuestionImport(), $file, 'admin');
        return $this->success('导入完成!');
    }

    /**
     * Build a form here.
     */
    public function form()
    {
        $this->file('file', '请选择文件')
            ->disk('admin')
            ->autoUpload()
            ->accept('xlsx,xls,csv');
    }
}

  • 弹窗显示
    运行 php artisan admin:action 命令,选择选项 3
php artisan admin:action
Which type of action would you like to make?:
  [0] default
  [1] grid-batch
  [2] grid-row
  [3] grid-tool
  [4] form-tool
  [5] show-tool
  [6] tree-tool

修改:

<?php

namespace App\Admin\Actions\Grid;

use App\Admin\Forms\QuestionData;
use Dcat\Admin\Admin;
use Dcat\Admin\Grid\Tools\AbstractTool;

class GridQuestionData extends AbstractTool
{
    /**
     * @return string
     */
    protected $title = '导入';

    protected function script()
    {
        $url = request()->fullUrlWithQuery(['gender' => '_gender_']);

        return <<<JS
$('input:radio.user-gender').change(function () {
    var url = "$url".replace('_gender_', $(this).val());
    Dcat.reload(url);
});
JS;
    }

    public function render()
    {
        Admin::script($this->script());
        $id = "DATA_IMPORT";
        $this->modal($id);
        return <<<HTML
<span data-toggle="modal" data-target="#{$id}" style="float: right">
   <a class="btn btn-primary btn-outline" style="color: #4199de"><i class="feather icon-share"></i>  导入</a>
</span>
HTML;
    }

    protected function modal($id)
    {
        // 表单
        $form = new QuestionData();
        Admin::html(
            <<<HTML
<div class="modal fade" id="{$id}">
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title">导入数据</h4>
         <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
      </div>
      <div class="modal-body">
        {$form->render()}
      </div>
    </div>
  </div>
</div>
HTML
        );
    }
}

  • 在grid 工具栏 使用
//导入
$grid->tools(new GridQuestionData());

表格

模型树

表结构和模型

使用model-tree,要遵守约定的表结构。表格结构里面有三个必要的字段parent_id、order、title,表结构中的三个字段parent_id、order、title的字段名也是可以修改的(修改为:sort_p_id、sort_name),parent_id字段一定要默认为0

CREATE TABLE `shiyu_sort`  (
  `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `sort_name` varchar(191) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL,
  `sort_desc` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL,
  `sort_p_id` int(11) NULL DEFAULT 0,
  `created_at` timestamp(0) NULL DEFAULT NULL,
  `updated_at` timestamp(0) NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = MyISAM AUTO_INCREMENT = 5 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci ROW_FORMAT = Dynamic;
对应的模型
namespace App\Models\Blog;

use Dcat\Admin\Traits\HasDateTimeFormatter;

use Dcat\Admin\Traits\ModelTree;
use Illuminate\Database\Eloquent\Model;

class ShiyuSort extends Model
{
	use HasDateTimeFormatter;
    use ModelTree;
    protected $table = 'shiyu_sort';
    // 父级ID字段名称,默认值为 parent_id
    protected $parentColumn = 'sort_p_id';

    // 排序字段名称,默认值为 order
    protected $orderColumn = 'id';

    // 标题字段名称,默认值为 title
    protected $titleColumn = 'sort_name';
}
页面使用方法
namespace App\Admin\Controllers\Blog;

use App\Models\Blog\ShiyuSort;
use Dcat\Admin\Form;
use Dcat\Admin\Layout\Row;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Tree;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Controllers\AdminController;

class ShiyuSortController extends AdminController
{
    public function index(Content $content)
    {
        return $content->header('分类')
            ->body(function (Row $row) {
                $tree = new Tree(new ShiyuSort);
                $row->column(12, $tree);
            });
    }
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new ShiyuSort(), function (Grid $grid) {
            $grid->column('id')->sortable();
            $grid->column('sort_name');
            $grid->column('sort_desc');
            $grid->column('sort_p_id');
            $grid->column('created_at');
            $grid->column('updated_at')->sortable();

            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');

            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new ShiyuSort(), function (Show $show) {
            $show->field('id');
            $show->field('sort_name');
            $show->field('sort_desc');
            $show->field('sort_p_id');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new ShiyuSort(), function (Form $form) {
            $menuModel = "App\Models\Blog\ShiyuSort";
            $form->display('id');
            $form->text('sort_name');
            $form->text('sort_desc');
            $form->select('sort_p_id')->options(function () use ($menuModel) {
                return $menuModel::selectOptions();
            })->saving(function ($v) {
                return (int)$v;
            });
            $form->display('created_at');
            $form->display('updated_at');
        });
    }
}

表单

下拉框

  • 单选
$form->select('subject_set')->options(function () {
        $roleModel = Major::class;
        return $roleModel::all()->pluck('major_name', 'id');
})->required();
  • 多选
$form->multipleSelect('subject_set')
    ->options(function () {
        $roleModel = Major::class;
        return $roleModel::all()->pluck('major_name', 'id');
    })
    //从数据库中查出的二维数组中转化成ID
    ->customFormat(function ($v) {
        return array_column($v, 'id');
    });

弹窗选择

  • 单选(2.0版本弃用)
// 方法1
$form->selectResource('questype_id', '题型')->path('/TiKu/Questype')
    ->multiple(1) // 设置为单选
    ->options(function ($v) {
        if (!$v) return $v;
        return Questype::find($v)->pluck('type_name', 'id');
    });

// 方法2
$menuModel = "App\Models\Blog\ShiyuSort";
$form->select('sort_p_id')->options(function () use ($menuModel) {
        return $menuModel::selectOptions();
    })->saving(function ($v) {
        return (int)$v;
    });
  • 多选(2.0版本弃用)
$form->selectResource('major_id', '申报专业')->path('/TiKu/Major')
    ->multiple() // 设置为多选
    ->options(function ($v) {
        if (!$v) return $v;
        return Major::find($v)->pluck('major_name', 'id');
    });
  • 弹窗选择新方法
//单选 (selectTable )
$this->multipleSelectTable('recent_news')->title('弹窗标题')
            ->dialogWidth('50%') // 弹窗宽度,默认 800px
            ->from(ShiyuArticleTable::make(['id' => $this->getKey()])) // 设置渲染类实例,并传递自定义参数
            ->model(ShiyuArticle::class, 'id', 'artcles_title'); // 设置编辑数据显示
//多选 (multipleSelectTable)
$this->multipleSelectTable('recent_news')->title('弹窗标题')
            ->dialogWidth('50%') // 弹窗宽度,默认 800px
            ->from(ShiyuArticleTable::make(['id' => $this->getKey()])) // 设置渲染类实例,并传递自定义参数
            ->model(ShiyuArticle::class, 'id', 'artcles_title') // 设置编辑数据显示
            ->saving(function ($v) {
                // $v 是表单提交的字段值,默认是数组类型,这里需要手动转换一下
                // 保存为以 "," 隔开的字符串,如果是多对多关联关系,则不需要转换。
                return implode(',', $v);
            });

定义渲染类如下,需要继承Dcat\Admin\Grid\LazyRenderable

namespace App\Admin\Renderable;

use App\Models\Blog\ShiyuArticle;
use Dcat\Admin\Grid;
use Dcat\Admin\Grid\LazyRenderable;

class ShiyuArticleTable extends LazyRenderable
{
    public function grid(): Grid
    {
        // 获取外部传递的参数
        $id = $this->id;
        return Grid::make(new ShiyuArticle(), function (Grid $grid) {
            $grid->column('id')->sortable();
            $grid->column('artcles_title','文章标题');
            $grid->column('artcles_views','浏览量');
            $grid->column('artcles_likes','点赞数');
            $grid->column('created_at');
            $grid->column('updated_at')->sortable();

            // 如果表格数据中带有 “name”、“title”或“username”字段,则可以不用设置
            $grid->rowSelector()->titleColumn('artcles_title');

            $grid->quickSearch(['id', 'artcles_title']);

            $grid->paginate(10);
            $grid->disableActions();

//            $grid->filter(function (Grid\Filter $filter) {
//                $filter->like('artcles_title')->width(4);
//            });
        });
    }
}

json字段

$form->table('exam_set', function ($table) {
                $table->select('subject_set', '题型')->options(function () {
                    $roleModel = Questype::class;
                    return $roleModel::all()->pluck('type_name', 'id');
                });
                $table->number('count', '数量');
                $table->number('score', '每题分值');
            })->saving(function ($v) {
                return json_encode($v);//转为json格式
            });

标签 (tags)

插入逗号(,)隔开的字符串tags,注意:处理ManyToMany关系时必须调用pluck方法,指定显示的字段名和主键。 此外 options 方法传入一个Collection对象时,options会自动调用该对象的pluck方法转为[‘主键名’ => ‘显示字段名’] 数组,作为下拉框选项。或者可以直接使用[‘主键名’ => ‘显示字段名’]这样的数组作为参数。
格式化待渲染的数据 (customFormat),通过customFormat方法把从数据库查出的字段值转化为array格式。

            $form->tags('artcles_label')
                ->pluck('tag_name', 'id')
                ->options(ShiyuTag::all())
                ->customFormat(function ($v){
                    if (!$v) return $v;
                    $tag = ShiyuTag::find($v)->pluck('tag_name', 'id');
                    return $tag;
                })
                ->saving(function ($value) {
                    return $value;
                });

自定义页面

首先控制器代码:

namespace App\Admin\Controllers\Shiyu;

use App\Admin\Forms\ShiyuIndex;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Controllers\AdminController;
use Dcat\Admin\Widgets\Card;

class ShiyuInddexController extends AdminController
{
    public function index(Content $content)
    {
        return $content->title('主页配置')
            ->body(new Card(new ShiyuIndex()));
    }
}

Form表单

namespace App\Admin\Forms;

use App\Models\Shiyu\ShiyuInddex;
use Dcat\Admin\Widgets\Form;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpFoundation\Response;

class ShiyuIndex extends Form
{
    // 处理表单提交请求
    public function handle(array $input)
    {
        $data = $input;
        $ShiyuInddex = new ShiyuInddex();

        if ($res = $ShiyuInddex->where('id', 1)->update($data)) {
            DB::commit();
        } else {
            DB::rollBack();
            return $this->error('Your error message.');
        }
        return $this->success('更新成功', 'Shiyu/ShiyuInddex');
    }

    // 构建表单
    public function form()
    {
        $this->confirm('您确定要提交表单吗', 'content');
        $this->text('id')->display(false);
        $this->text('title');
        $this->image('logo')->autoUpload();
        $this->url('yuming');
        $this->multipleImage('lbt_images')->limit(3)->autoUpload();
        $this->table('lbt_text_1', function ($table) {
            $table->textarea('lbt1_1');
            $table->textarea('lbt1_2');
            $table->textarea('lbt1_3');
        })->saving(function ($v) {
            return json_encode($v);
        });
        $this->table('lbt_text_2', function ($table) {
            $table->textarea('lbt2_1');
            $table->textarea('lbt2_2');
            $table->textarea('lbt2_3');
        })->saving(function ($v) {
            return json_encode($v);
        });
        $this->text('recent_photography');
        $this->multipleImage('teams_images')->limit(5)->autoUpload();
        $this->table('teams_text', function ($table) {
            $table->text('people_name');
            $table->textarea('people_msg');
        })->saving(function ($v) {
            return json_encode($v);
        });
        $this->text('contact_text');
        $this->text('feedback_text');
        $this->text('recent_news');
        $this->text('footer_text');
        $this->display('created_at');
        $this->display('updated_at');
    }

    /**
     * 返回表单数据
     *
     * @return array
     */
    public function default()
    {
        $data = ShiyuInddex::find(1)->get()->toArray();
        return $data[0];
    }
}

根据前台json数组,动态建表

做的时候,$data总是传不到Schema::create('stmt_plan_list', function ($table){...}里,自己错误写法是这样的:

 Schema::create('stmt_plan_list', function ($table,$data) {
     ....
 }

正确写法应该是用 use ($data)

->saved(function (Form $form, $result) {
            if(!Schema::hasTable('stmt_plan_list')){
                $data = $form->updates();
                $data = json_decode($data['plan_create_table']);//字段数组
                Schema::create('stmt_plan_list', function ($table) use ($data) {
                    $table->increments('id')->comment('主键');
                    for ($i = 0;$i<count($data);$i++){
                        if($data[$i]->table_type == 'varchar'){
                            $table->string($data[$i]->table_name)->comment($data[$i]->table_desc);
                        }
                        if($data[$i]->table_type == 'int'){
                            $table->integer($data[$i]->table_name)->comment($data[$i]->table_desc);
                        }
                        if($data[$i]->table_type == 'decimal'){
                            $table->decimal($data[$i]->table_name, 10, 2)->comment($data[$i]->table_desc);
                        }
                    }
                    $table->timestamps();
                });
            }
        });
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值