【Laravel】Laravel-admin后台框架-2创建数据表建立模块增删改查CURD(1)

前言

前面我们已经能够完整创建Laravel-admin的项目了,接下来要在做中学,学习如何实际创建一个符合业务的模块,完成CURD的操作。

实战

定义业务

业务:比如我们要做个健身教练录入上课训练的记录,记录每次教学的情况。

设计数据表

目前只做一张表,后续再迭代。

CREATE TABLE `fit_record` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `user_name` varchar(255) NOT NULL DEFAULT '' COMMENT '用户名称',
  `admin_id` int(11) unsigned NOT NULL COMMENT '教练名称',
  `class_time` time NOT NULL COMMENT '上课时间',
  `star` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT '评分',
  `date` date NOT NULL COMMENT '日期',
  `remark` varchar(500) NOT NULL DEFAULT '' COMMENT '总结',
  `created_at` datetime NOT NULL COMMENT '创建时间',
  `updated_at` datetime NOT NULL COMMENT '更新时间',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COMMENT='课程记录表';

创建模型

lixiaoyu@localhost fit % composer require reliese/laravel
    1/13:	https://mirrors.aliyun.com/composer/p/provider-archived$52c8dd62b281440663b1f30ca24e96ff31ead2f625af3ee85487abb1ad7929b8.json
    2/13:	https://mirrors.aliyun.com/composer/p/provider-2019-07$a244f7ffcdbae34f7bc0b0429cde5b2e506ee8e3c27ad47792c4e2a934a43647.json
    3/13:	https://mirrors.aliyun.com/composer/p/provider-2015$8560c0f524832933b1e7e2ee13aee2ab7733008eda885fbe1f784eab5652d0f7.json
    4/13:	https://mirrors.aliyun.com/composer/p/provider-2019-10$057ca9a7b38aeef220511ee9dfb8846a0bf677bb3ccce6392e163a8d9d8ac6e2.json
    5/13:	https://mirrors.aliyun.com/composer/p/provider-2013$0332a3aa11cf0cbe03d02cc56124f22c14e38846fcf01674d6732f6db01c1119.json
    6/13:	https://mirrors.aliyun.com/composer/p/provider-2014$270468bbe7b61b879a2a54169b471353c86318e4a9e1b40851d6763989d42e08.json
    7/13:	https://mirrors.aliyun.com/composer/p/provider-2019$cc2fc124e2fdb7f586f597a3e2f49219548f6c489fa91802b5a849c8c4887d75.json
    8/13:	https://mirrors.aliyun.com/composer/p/provider-latest$fd0ad9c5fb4d252916129e185cdf1250f26de2aa36f05395c65c1f0ff4adcce6.json
    9/13:	https://mirrors.aliyun.com/composer/p/provider-2017$a23758a1eeb4bcda969878ebb62f452ce904f319fccc9deec62d6674f6d93806.json
    10/13:	https://mirrors.aliyun.com/composer/p/provider-2020-01$76eb865fc55298c6e7edd8176c30978bcc676e3be254a3fb044cf4c620fdc114.json
    11/13:	https://mirrors.aliyun.com/composer/p/provider-2020-04$05757647de7ff0e2c4d67553023fcc56ce91eced6ae49c6dcda45fd2a710bb08.json
    12/13:	https://mirrors.aliyun.com/composer/p/provider-2016$137b5465b9ee2d71731e79e23efdb0eb613bb3dd94b839c8f7331ef1ecc4995c.json
    13/13:	https://mirrors.aliyun.com/composer/p/provider-2018$6b1f4cd011f8668c7aa58d37879b462b8abcaebe07a55adec2d1fb1eb87490a5.json
    Finished: success: 13, skipped: 0, failure: 0, total: 13
Using version ^0.0.16 for reliese/laravel
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
    1/1:	https://mirrors.aliyun.com/composer/dists/reliese/laravel/f4a95c8a37d1c0b117939d7d8660119474d1704b.zip
    Finished: success: 1, skipped: 0, failure: 0, total: 1
Package operations: 1 install, 0 updates, 0 removals
  - Installing reliese/laravel (v0.0.16): Loading from cache
Writing lock file
Generating optimized autoload files
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> @php artisan package:discover --ansi
Discovered Package: encore/laravel-admin
Discovered Package: facade/ignition
Discovered Package: fideloper/proxy
Discovered Package: fruitcake/laravel-cors
Discovered Package: laravel/tinker
Discovered Package: nesbot/carbon
Discovered Package: nunomaduro/collision
Discovered Package: reliese/laravel
Package manifest generated successfully.
46 packages you are using are looking for funding.
Use the `composer fund` command to find out more!

修改config/app.php找到providers添加如下内容

Reliese\Coders\CodersServiceProvider::class,
lixiaoyu@localhost fit % php artisan vendor:publish --tag=reliese-models
Copied File [/vendor/reliese/laravel/config/models.php] To [/config/models.php]
Publishing complete.
lixiaoyu@localhost fit % php artisan config:clea
Configuration cache cleared!
lixiaoyu@localhost fit % php artisan code:models
Check out your models for laravel
lixiaoyu@localhost fit % ls app/Models 
AdminMenu.php		AdminPermission.php	AdminRoleMenu.php	AdminRoleUser.php	AdminUserPermission.php	FitRecord.php
AdminOperationLog.php	AdminRole.php		AdminRolePermission.php	AdminUser.php		FailedJob.php		User.php

你就能看到全部的表都创建了对应的模型。

创建控制器

lixiaoyu@localhost fit % php artisan admin:make RecordController --model=App\\Models\\FitRecord
App\Admin\Controllers\RecordController created successfully.

Add the following route to app/Admin/routes.php:

    $router->resource('fit-records', RecordController::class);

接下来按说明在app/Admin/routes.php添加

	$router->resource('record', RecordController::class);

控制器已经自动创建在了App\Admin\Controllers\RecordController,已经默认使用了模型并创建了对应的表单

内容如下:

namespace App\Admin\Controllers;

use App\Models\FitRecord;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;

class RecordController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = 'FitRecord';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new FitRecord());

        $grid->column('id', __('Id'));
        $grid->column('user_name', __('User name'));
        $grid->column('admin_id', __('Admin id'));
        $grid->column('class_time', __('Class time'));
        $grid->column('star', __('Star'));
        $grid->column('date', __('Date'));
        $grid->column('remark', __('Remark'));
        $grid->column('created_at', __('Created at'));
        $grid->column('updated_at', __('Updated at'));

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(FitRecord::findOrFail($id));

        $show->field('id', __('Id'));
        $show->field('user_name', __('User name'));
        $show->field('admin_id', __('Admin id'));
        $show->field('class_time', __('Class time'));
        $show->field('star', __('Star'));
        $show->field('date', __('Date'));
        $show->field('remark', __('Remark'));
        $show->field('created_at', __('Created at'));
        $show->field('updated_at', __('Updated at'));

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new FitRecord());

        $form->text('user_name', __('User name'));
        $form->number('admin_id', __('Admin id'));
        $form->datetime('class_time', __('Class time'))->default(date('Y-m-d H:i:s'));
        $form->switch('star', __('Star'));
        $form->date('date', __('Date'))->default(date('Y-m-d'));
        $form->text('remark', __('Remark'));

        return $form;
    }
}

可以看到的是,这个控制器继承了AdminController,他里面写了对应的create,show,edit,list方法

一般情况下都是不能满足业务需求的,所以需要自己写。

访问地址

创建之后,对应的地址是http://fit.local/admin/record,其中fit.loca是我自己本地定义的。

【Laravel】Laravel-admin后台框架-2创建数据表建立模块增删改查CURD(1)_第1张图片

完善创建功能

目前的创建是这样的

【Laravel】Laravel-admin后台框架-2创建数据表建立模块增删改查CURD(1)_第2张图片
需要完善的部分

  • 描述相关改成中文
  • 修改表单顺序
  • 隐藏admin_id默认为当前登录用户的id
  • star改成0到5的range
  • 表单字段改成中文
  • 去掉不需要的按钮比如重置

model

namespace App\Models;

use Carbon\Carbon;
use Encore\Admin\Admin;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;

/**
 * Class FitRecord
 *
 * @property int $id
 * @property string $user_name
 * @property int $admin_id
 * @property Carbon $class_time
 * @property bool $star
 * @property Carbon $date 日期
 * @property string $remark 备注
 * @property int $created_at
 * @property int $updated_at
 *
 * @package App\Models
 */
class FitRecord extends Model
{
	protected $table = 'fit_record';

	protected $casts = [
		'admin_id' => 'int',
		'star' => 'bool',
		'created_at' => 'datetime',
		'updated_at' => 'datetime'
	];

	protected $dates = [
		'class_time',
		'date'
	];

	protected $fillable = [
		'user_name',
		'admin_id',
		'class_time',
		'star',
		'date',
		'remark'
	];

	public static $label = [
	    'user_name'=>'用户名',
        'star'=>'评分',
        'date'=>'日期',
        'class_time'=>'开始时间',
        'remark'=>'备注',
        'created_at' => '创建时间',
        'updated_at' => '修改时间'
    ];


	public function __construct(array $attributes = [])
    {
        if($this->id == null){
            $this->admin_id = \Encore\Admin\Facades\Admin::user()->id; //初始化管理员id
        }
        parent::__construct($attributes);
    }
}

controller

    protected function form()
    {
        $form = new Form(new FitRecord());

        $form->tools(function (Form\Tools $tools) {
            $tools->disableList();
            $tools->disableDelete();
            $tools->disableView();

        });

        $form->footer(function ($footer) {
            $footer->disableReset();;
            $footer->disableViewCheck();
            $footer->disableEditingCheck();
        });

        $form->text('user_name', FitRecord::$label['user_name']);
        $form->time('class_time',   FitRecord::$label['class_time'])->default(date('H:i:s'));
        $form->number('star', FitRecord::$label['star'])->min(0)->max(5)->default(5);
        $form->date('date',FitRecord::$label['date'])->default(date('Y-m-d'));
        $form->textarea('remark', FitRecord::$label['remark']);

        $form->display('created_at', '创建时间');
        $form->display('updated_at', '修改时间');
        return $form;
    }

修改完成对应的模型和视图之后,页面展示如下

【Laravel】Laravel-admin后台框架-2创建数据表建立模块增删改查CURD(1)_第3张图片

到此完成了数据新增的修改。

总结

  • 自动创建模型
  • 修改模型规则
  • 显示字段注释
  • 构造函数写入登录用户id

参考资料

  • https://github.com/reliese/laravel
  • https://learnku.com/docs/laravel/7.x/authentication/7474

你可能感兴趣的:(#,PHP问题集锦,laravel,php)