You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

85 lines
2.3 KiB

<?php
namespace App\Http\Requests;
use App\Exceptions\ErrorException;
use App\Models\BaseForm;
use App\Models\CustomFormField;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class BaseFormRequest extends FormRequest
{
public $tableName;
public $customForm;
public $customFormFields;
public function __construct()
{
$model = new BaseForm();
$this->tableName = $model->tableName;
$this->customForm = $model->customForm;
$this->customFormFields = CustomFormField::where('custom_form_id', $this->customForm->id)->whereNotNull('validation')->get();
}
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
$id = request('id');
$rules = [];
foreach ($this->customFormFields as $item) {
$validation = $item->validation;
if (in_array('unique', $validation)) {
$key = array_search('unique', $validation);
// 唯一检测,排除自身
$unique = Rule::unique($this->tableName);
if ($id) $unique = $unique->ignore($id);
$validation[$key] = $unique;
}
$rules[$item->field] = implode('|', $validation);
}
return $rules;
}
public function messages()
{
$validationRules = CustomFormField::$validationRules;
$msg = [];
foreach ($this->customFormFields as $key => $item) {
foreach ($item->validation as $k => $v) {
$msg[$item->field . '.' . $v] = $item->name . $validationRules[$v] . '检测不通过';
}
}
return $msg;
}
protected function failedValidation(Validator $validator)
{
$msgArray = $validator->errors()->toArray();
$list = [];
foreach ($msgArray as $key => $item) {
$list[$key] = implode(',', $item);
}
$list = array_values($list);
$str = implode(',', $list);
throw new ErrorException($str);
}
}