一个网站后台,大部分都是增删改成,可以说除了个别应用之后,其他都是增删改成。
Laravel的访问入口,必须先定义好路由之后,才能访问,那么我们第一步就是认识路由。

KongQi Laravel Admin路由怎么定义

routes/admin.php

<?php
$admin_path = 'admin';
/*****************无需验证中间件**********************/
//无需验证权限,或者里面验证
Route::prefix($admin_path)->middleware(['install'])->name('admin.')->group(function ($route) {
    $route->get('/login', 'LoginController@showLoginForm')->name('login');
    $route->post('login', 'LoginController@login')->name('post.login');
    $route->get('logout', 'LoginController@logout')->name('logout');
});

/*****************验证中间件**********************/
Route::prefix($admin_path)->middleware(['install', 'admin_auth', 'admin_check'])->name('admin.')->group(function ($route) {
    $route->get('home', 'HomeController@console')->name('home.console');
    $route->get('clear/cache', 'HomeController@clearCache')->name('home.clear.cache');
    $route->get('/', 'HomeController@index')->name('home');
    $route->get('/admin_plugin/{ename}', 'HomeController@plugin')->name('home.plugin');

    $route->any('upload/{type}', ['uses' => 'FileUploadController@handle'])->name('upload');
    $route->any('icon', ['uses' => 'IconController@index'])->name('icon');
    $route->any('error/{code}', ['uses' => 'ErrorController@index'])->name('error');
    $route->any('excel/import', ['uses' => 'ExcelController@import'])->name('excel.import');

    //增删改查存放的控制器数组
    $resource = [
        'AdminController',
        'AdminRoleController',
        'AdminPermissionController',
        'CategoryController',
        'PluginController'
    ];
    //需要批量操作
    $more_add_controller = [
        'AdminPermissionController',
    ];
    //只需要首页
    $only_index_controller = [
        'AdminLogController',
    ];
    //
    $only_add_controller = [
        'ConfigController'
    ];

    //需要表格导入
    $import_add_controller = [
        'AdminPermissionController'
    ];
    //管理员修改密码
    $route->get('admin/password', 'AdminController@password')->name("admin.password");
    $route->post('admin/password', 'AdminController@passwordPost')->name("admin.password_post");
    foreach ($resource as $c) {
        //自动获取
        $controller = str_replace('Controller', '', $c);
        $controller_path = strtolower($controller);
        $route->group(['prefix' => $controller_path . '/'], function ($route) use ($c, $controller_path) {
            $route->get('/', $c . '@index')->name($controller_path . ".index");

            $route->get('create', $c . '@create')->name($controller_path . ".create");
            $route->get('show/{id}', $c . '@show')->name($controller_path . ".show");
            $route->post('store', $c . '@store')->name($controller_path . ".store");
            $route->get('edit/{id}', $c . '@edit')->name($controller_path . ".edit");
            $route->put('update/{id}', $c . '@update')->name($controller_path . ".update");
            $route->put('delete/', $c . '@destroy')->name($controller_path . ".destroy");
            $route->post('edit_list/', $c . '@editTable')->name($controller_path . ".edit_list");
        });

        $route->any($controller_path . '/list', ['uses' => $c . '@getList'])->name($controller_path . ".list");

        //增加批量操作
        if (in_array($c, $more_add_controller)) {
            $route->get($controller_path . '/all/create', ['uses' => $c . '@allCreate'])->name($controller_path . '.all_create');
            $route->post($controller_path . '/all/create/post', ['uses' => $c . '@allCreatePost'])->name($controller_path . '.all_create_post');
        }
        //导入操作
        if (in_array($c, $more_add_controller)) {
            $route->post($controller_path . '/import/post', ['uses' => $c . '@importPost'])->name($controller_path . '.import_post');
            $route->get($controller_path . '/import/tpl', ['uses' => $c . '@importTpl'])->name($controller_path . '.import_tpl');
        }

        //额外增加
        if(in_array($c,['PluginController']))
        {

            $route->post($controller_path . '/install/{ename}/{type}', ['uses' => $c . '@install'])->name($controller_path . '.install');
        }
    }

    foreach ($only_index_controller as $c) {
        $controller = str_replace('Controller', '', $c);
        $controller_path = strtolower($controller);
        $route->group(['prefix' => $controller_path . '/'], function ($route) use ($c, $controller_path) {
            $route->get('/', $c . '@index')->name($controller_path . ".index");
            $route->any($c . '/list', ['uses' => $c . '@getList'])->name($controller_path . ".list");
        });

    }
    foreach ($only_add_controller as $c) {
        $controller = str_replace('Controller', '', $c);
        $controller_path = strtolower($controller);
        $route->group(['prefix' => $controller_path . '/'], function ($route) use ($c, $controller_path) {
            $route->get('/', $c . '@index')->name($controller_path . ".index");
            $route->post('store', $c . '@store')->name($controller_path . ".store");
            $route->any($c . '/list', ['uses' => $c . '@getList'])->name($controller_path . ".list");
        });

    }

});
  • 大部分我把增删改成做成了循环列表去执行,那样的话,减少书写,更加统一。
  • 分了几个数组,分别去执行不一样的控制器方法绑定。

增删改查控制器长什么样

通常我们做增删改查的时候,都会写创建页面,编辑页面,列表页,删除,那么这里就最低至少包含了4个方法,在Laravel里面建议是分开,那么就变成了最低6个方法来完成, 对此,个人根据理解进行了增加,编辑,查询,删除,列表进行了封装,封装理由有如下:

  • 减少重复的轮子代码
  • 减少重复的代码赘余,保持统一风格,但又不缺少特殊性,完美的共性和个性结合。
  • 让代码尽可能的自动完成。

最简单一个增删控制器如下

<?php

namespace App\Plugin\Market\Admin;

use App\Plugin\AdminCurlController;
use App\Plugin\Market\Models\PnMarket;
use App\Plugin\Market\Models\PnMarketCategory;
use App\Plugin\Market\Models\PnMarketTag;
use App\Plugin\Note\Models\PnNoteCategory;
use Illuminate\Http\Request;

class MarketController extends BaseController
{
    public $pageName = '插件';
    //设置模型
    public function setModel()
    {
        return $this->model = new PnMarket();
    }
    //表单验证规则
    public function checkRule($id = '')
    {
        if (!$id) {
            return [
                'name' => [
                    "required",
                    "unique:pn_markets,name"
                ],
                'ename' => [
                    "required",
                    "unique:pn_markets,ename"
                ],

            ];
        }
        return [
            'name' => [
                "required",
                "unique:pn_markets,name," . $id
            ],
            'ename' => [
                "required",
                "unique:pn_markets,ename," . $id
            ],

        ];
    }
    //API JSON输出字段附加,需要返回$item
    public function apiJsonItemExtend($item)
    {

        $item->category_name=$item->category['name']??'';
        return $item;
    }
    //增加和编辑页面共享视图变量,需要返回数组
    public function createEditData($show = '')
    {
        $cate = PnMarketCategory::category();

        $tags=[];
        if ($show) {
            $tags=$show->getTags();
        }
        return ['category' => $cate,'tags'=>$tags];
    }
    //首页共享数组
    public function indexData()
    {
        $item = [];


        return $item;
    }
    //完成创建和编辑之后需要操作的事情,如果$id不为空,表示编辑的更新操作。
    public function afterSave($model, $id = '')
    {
        //标签添加
        $tags = $this->rq->input('tags');
        PnMarketTag::add($tags, $model->id, 'pn_market');

    }

}

这个只是基本的,如果我要附加懒加载关联呢,有方法的.

懒加载

//设置懒加载关联
public function setModelAddRelaction($model)
{
        return $model->with('Category'); 
}

开启事务

 //开启事务,直接返回1,表示开启事务,那么之后afterSave就需要返回`真`才能够提交数据。
    public function beginDb($data, $id = '')
    {
        return 1;
    }

事务提交之后需要操作的事件

   /**
     * 如果是事务提交,事务提交之后的操作的事情
     * @param $model
     * @param string $id
     */
    protected function beginAfterSave($model, $id = '')
    {

    }

更多的方法,请查看下面这个方法里面说明就懂了

protected function saveData($request, $model, $id = '')
    {
        $this->rq = $request;
        $error = $this->checkForm($request->all(), $this->checkRule($id), $this->checkRuleMsg(), $this->checkRuleField());
        if (count($error) > 0) {
            return $this->checkFormErrorFormat($error);
        };
        //附加检验
        $extend_check = $this->extendValidate($model, $id);
        if (is_array($extend_check)) {
            return response()->json($extend_check);
        }
        //设置请求参数
        $data = $this->postData($id);

        //参数赋值给模型
        $model = $this->setDbKeyValue($model, $data);
        $model = $this->addPostData($model);
        //是否开启事务
        $begin = $this->beginDb($data);
        //更新/添加之前要操作的事
        $this->beforeSave($model, $id);
        $model = $this->saveModelAddData($model, $id);
        //检测之前是否有问题
        if (count($this->modelSaveMsg) > 0) {
            return $this->returnErrorApi($this->modelSaveMsg['msg'], [], $this->modelSaveMsg['code']);
        }
        //$begin=1表示开启事务操作
        if ($begin != 0) {
            DB::beginTransaction();
            $result = $model->save();
            //插入/更新最后ID
            $result ? $this->modelInsertId = $model->id : '';
            //事务的操作,之后的需要返回真才能够完成,否则失败
            $after_result = $this->afterSave($model, $id);
            if ($result && $after_result) {
                DB::commit();
                $this->beginAfterSave($model, $id);
            } else {
                DB::rollback();
            }
        } else {
            //非事务操作
            $result = $model->save();
            $result ? $this->modelInsertId = $model->id : '';
            $this->afterSave($model, $id);
        }
        //返回信息
        return $this->saveMessage($result, $id);
    }

列表操作.

public function getList(Request $request)
    {
        $this->rq = $request;
        $offset = $request->input('page', 1);
        $pagesize = $request->input('limit', 30);
        $offset = ($offset - 1) * $pagesize;
        $order_by_name = $this->orderByName();
        $order_by_type = $this->orderByType();
        $debug = $request->input('debug', 0);
        //如果开始没有数据,直接返回空的

        if (!$this->getModel()) {
            return $this->returnApi(200, '没有初始化模型', []);
        }
        $model = $this->getSearchModel($this->setSearchParam($request->all()));
        $model=$this->addListSearch($model);
        $total = $model->count();
        //是否是否关联数据等操作
        $model = $this->setModelAddRelaction($model);
        $model = $model->skip($offset);
        $model = $this->orderBy($model, $order_by_name, $order_by_type);
        $result = $model->take($pagesize)->get();

        //显示内容设置
        $arr_data = $this->apiJsonData($result);
        return $this->listJsonFormat($total, $arr_data, $debug);
    }

这里主要操作的无非就说搜索条件和显示数据追加,搜索可以参考下面2个方法

 /**
     * 列表增加搜索地方
     * @param $model
     */
    public function addListSearch($model){
        return $model;
    }

也可以在QueryWhereTrait.php里面增加或者是插件里面SearchService,例如要增加搜索category_id这个字段

 public function addListSearch($model){
        $category=$this->rq->input('category_id');
                if($category){
                    $model=$model->where('category_id',$category);
                }
        return $model;
    }

SearchService.php/QueryWhereTrait.php 里面写

   public function whereByCategoryId($value)
    {
        $data = [
            'category_id' => [
                'type' => '=',
                'value' => $value
            ]
        ];
        $this->addWhere($data);
    }

建议都写在SearchService.php/QueryWhereTrait.php,减少轮子制造。

修改列表显示 内容

  /**
     * JSON 列表输出项目设置
     * @param $item
     * @return mixed
     */
    public function apiJsonItem($item)
    {
        $item['edit_url'] = action($this->route['controller_name'] . '@edit', ['id' => $item->id]);
        $item['edit_post_url'] = action($this->route['controller_name'] . '@update', ['id' => $item->id]);
        $item=$this->apiJsonItemExtend($item);
        return $item;
    }

    /**
     * 继续附加
     * @param $item
     * @return mixed
     */
    public function apiJsonItemExtend($item){
        return $item;
    }

更多操作,请查看代码。