laravel 制作通用的curd 后臺(tái)操作

[TOC]
在后臺(tái)簡(jiǎn)單的單表操作,我們一般會(huì)像下面這樣執(zhí)行curd:

改造前的controller文件

<?php

namespace App\Http\Controllers\Admin;

use App\Entity\Carmodel;
use App\Entity\Washfee;
use App\Entity\Washtype;
use App\Http\Requests\Admin\WashFeeRequest;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class WashFeesController extends Controller
{
    public function index()
    {

    }
    public function create(){
          return view('admin.washFees.create');
    }
    public function store(WashFeeRequest $washFeeRequest)
    {

        $data = [
            'car_id'      => $washFeeRequest->car_id,
            'wash_id'     => $washFeeRequest->wash_id,
            'price'       => $washFeeRequest->price,
            'create_time' => time(),
        ];
        if (!Washfee::create($data)) {
            $msg = '創(chuàng)建失敗';
        }else{
            $msg = '創(chuàng)建成功';
        }
        session()->flash('msg',$msg);
        return redirect()->route('washfees.index');
    }
    public function edit(Washfee $washfee){
            return view('admin.washFees.edit',compact('washfee');
    }
    public function update(WashFeeRequest $washFeeRequest, Washfee $washfee)
    {
        if ($washFeeRequest->isMethod('PUT')) {

            $washfee->car_id = $washFeeRequest->car_id;
            $washfee->wash_id = $washFeeRequest->wash_id;
            $washfee->price = $washFeeRequest->price;

            if (!$washfee->save()) {
                $msg = '修改失敗';
            }else{
                $msg = '修改成功';
            }
        }
        session()->flash('msg', $msg);
        return redirect()->route('washfees.index');
    }

    public function destroy(Washfee $washfee)
    {
        if (!$washfee->delete()) {
            $msg = '刪除失敗';
        } else {
            $msg = '刪除成功';
        }
        session()->flash('msg', $msg);
        return redirect()->back();
    }
}

我們發(fā)現(xiàn)所有的單表操作里面,store\update\destroy 這幾個(gè)方法幾乎都是一樣的,所以可以抽取這些方法的共性來(lái)提升我們的代碼可復(fù)用性。

前置條件:

  1. 所有的model都需要設(shè)置fillable這個(gè)屬性,至于為什么,后面說(shuō)
  2. 所有的controller的模型驗(yàn)證都是通過(guò)request類來(lái)進(jìn)行驗(yàn)證的
  3. 建立通用的curd trait

改造后的代碼:

  1. model文件
<?php

namespace App\Entity;

use Illuminate\Database\Eloquent\Model;

class AuthGroup extends Base
{
    protected $table = 'auth_group';
    protected $fillable = ['title','description','status','rules','deleted_at'];//此處必須設(shè)置
}
  1. request文件
<?php

namespace App\Http\Requests\Admin;

use Illuminate\Foundation\Http\FormRequest;

class AuthGroupRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        $authGroup = $this->route('authGroup');
        return [
            'title'       => 'required|min:2|unique:auth_group,title,' . $authGroup['id'] . ',id',
            'description' => 'nullable',
            'status'      => 'between:0,1'
        ];
    }
}
  1. 新增加的commonCurd文件
<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Http\FormRequest;

trait CommonCURD
{
public function commonUpdate(FormRequest $request, Model $model)
    {
        //循環(huán)model的fillable,如果request存在該鍵,則更新
        foreach ($model->getFillable() as $key) {
            if ($request->has($key)) {
                $model->$key = $request->$key;
            }
        }
        //保存
        if (!$model->save()) {
            $msg = '修改失敗';
            session()->flash('msg', $msg);
        } else {
            $msg = '修改成功';
            session()->flash('msg', $msg);
        }
    }

    public function commonStore(FormRequest $request, $model)
    {
        $data = [];
        $m = new $model;
        foreach($m->getFillable() as $key){
            if($request->has($key)){
                $data[$key] = $request->$key;
            }
        }
        if (!$model::create($data)) {
            $msg = '創(chuàng)建失敗';
        }else{
            $msg = '創(chuàng)建成功';
        }
        session()->flash('msg',$msg);
    }

    public function commonDestroy(Model $model)
    {
        if (!$model->delete()) {
            $msg = '刪除失敗';
        } else {
            $msg = '刪除成功';
        }
        session()->flash('msg', $msg);
    }
}
  1. 改造后的controller文件,我用了另一個(gè)文件演示改造后的代碼
<?php

namespace App\Http\Controllers\Admin;

use App\Entity\AuthGroup;
use App\Http\Requests\Admin\AuthGroupRequest;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class AuthGroupsController extends Controller
{
    use CommonCURD;//引入trait
    public function index()
    {
        
    }
    public function create()
    {
        $title = '用戶組';
        return view('admin.authGroups.create', compact('title'));
    }
    public function store(AuthGroupRequest $authGroupRequest)
    {
        //改造后代碼
        $this->commonStore($authGroupRequest,WashFee::class);
        return redirect()->route('authGroups.index');
    }

    public function edit(AuthGroup $authGroup)
    {
        $title = '用戶組';
        return view('admin.authGroups.edit', compact('title', 'authGroup'));
    }

    public function update(AuthGroupRequest $authGroupRequest, AuthGroup $authGroup)
    {  
        //改造后的代碼,如果該model屬性多的話可以減少很多的代碼量
        $this->commonUpdate($authGroupRequest, $authGroup);
        return redirect()->route('authGroups.index');
    }

    public function destroy(AuthGroup $authGroup)
    {
        $this->commonDestroy($authGroup);
        return redirect()->route('authGroups.index');
    }
}

下面是我在提交update時(shí)打印的數(shù)據(jù):


image.png

可以看到原始數(shù)據(jù)和修改后的數(shù)據(jù),并且沒(méi)有提交的數(shù)據(jù)是不變的(有些字段在表單里面沒(méi)有)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容