我经常使用的方法是为我的模型编写一个HasRules trait,它看起来像这样:
trait HasRules
{
public static function getValidationRules(): array
{
if (! property_exists(static::class, 'rules')) {
return [];
}
if (func_num_args() === 0) {
return static::$rules;
}
if (func_num_args() === 1 && is_string(func_get_arg(0))) {
return array_get(static::$rules, func_get_arg(0), []);
}
$attributes = func_num_args() === 1 && is_array(func_get_arg(0))
? func_get_arg(0)
: func_get_args();
return array_only(static::$rules, $attributes);
}
}
看起来很乱,但它的作用是允许您以多种方式检索您的规则(如果存在,则从静态字段中)。因此,在您的模型中,您可以:
class User extends Model
{
use HasRules;
public static $rules = [
'name' => ['required'],
'age' => ['min:16']
];
...
}
然后在您的验证中(例如,在您的FormRequest 的rules() 方法中或在准备规则数组时的控制器中)您可以通过多种方式调用此getValidationRules():
$allRules = User::getValidationRules(); // if called with no parameters all rules will be returned.
$onlySomeRules = [
'controller_specific_field' => ['required'],
'name' => User::getValidationRules('name'); // if called with one string parameter only rules for that attribute will be returned.
];
$multipleSomeRules = User::getValidationRules('name', 'age'); // will return array of rules for specified attributes.
// You can also call it with array as first parameter:
$multipleSomeRules2 = User::getValidationRules(['name', 'age']);
不要害怕编写一些代码来生成您的自定义控制器特定规则。使用array_merge 和其他助手,实现你自己的(例如,一个助手将'required' 值添加到数组中,如果它不存在或删除它等)。不过,我强烈建议您使用 FormRequest 类来封装该逻辑。