«

Laravel FormRequest Prepare 预处理

时间:2025-6-6 14:22     作者:wanzi     分类: php


使用 FormRequest的时候,也许会想到给字段验证前填充一下字段的默认值,我们基于laravel的方式应该怎么做?


<?php

namespace App\Http\Requests\Admin;

use Illuminate\Foundation\Http\FormRequest;

class PlanSave extends FormRequest
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name' => 'required',
            'content' => '',
            'group_id' => 'nullable|integer',

        ];
    }

    public function messages()
    {
        return [
            'name.required' => '套餐名称不能为空',
            'type.required' => '套餐类型不能为空',
            'type.in' => '套餐类型格式有误',
//            'group_id.required' => '权限组不能为空',

        ];
    }

    /**
     * 准备数据以进行验证。
     * @return void
     */
    protected function prepareForValidation(): void
    {
        $this->merge([
            'group_id' => $this->group_id ?? 0,
        ]);
    }
}