[英]When updating a row, how do I validate that the existing row contains a value with Laravel form requests?
In Laravel 5, using a form request to act as a validation gate, and given the code below: 在Laravel 5中,使用表单请求作为验证门,并给出以下代码:
Controller 调节器
public function decline(Request $request, InviteDeclineRequest $validation, $id)
{
$invite = Invite::find($id);
$invite->status = 'declined';
$invite->save();
}
FormRequest FormRequest
class InviteDeclineRequest extends Request {
public function rules()
{
return [
# this is referring to the incoming data,
# not the existing data
'status': 'pending',
];
}
}
How can I change the above validation ruleset to say, the incoming input is only valid if the existing record's status is set to 'pending'. 我如何更改上述验证规则集以说,仅当现有记录的状态设置为“待处理”时,传入输入才有效。 Ie don't allow a declined invite unless the existing is pending. 也就是说,除非现有邀请待处理,否则不允许拒绝邀请。
Option 1: Put this logic in the controller. 选项1:将此逻辑置于控制器中。 Maybe the above isn't considered a part of validation, (although I would argue that it is), and so doesn't belong in the FormRequest. 也许以上内容不被认为是验证的一部分(尽管我认为是这样),所以它不属于FormRequest。
Option 2: Put the logic in the Authorise method of method of the FormRequest. 选项2:将逻辑放在FormRequest方法的Authorize方法中。 The only downside to this is that the authorise should be for access control, not data validation. 唯一的缺点是授权应该用于访问控制,而不是数据验证。
Option 3: Extend form request to include a third method that validates existing data as well as incoming data. 选项3:扩展表单请求以包括第三种方法,该方法可以验证现有数据以及传入数据。 Slightly painful as I need to make sure it gets called as part of the request cycle. 有点痛苦,因为我需要确保在请求周期中调用它。
Option 4: Add a custom validation rule: http://laravel.com/docs/5.0/validation#custom-validation-rules 选项4:添加自定义验证规则: http : //laravel.com/docs/5.0/validation#custom-validation-rules
You can add to your custom InviteDeclineRequest
class method all
to add id
to data that will be validated: 您可以将all
添加到自定义InviteDeclineRequest
类方法中,以将id
添加到将要验证的数据中:
public function all()
{
$data = parent::all();
$segments = $this->segments();
$id = intval(end($segments));
if ($id != 0) {
$data['id'] = $id;
}
return $data;
}
and now in rules
you can use it: 现在在rules
您可以使用它:
public function rules()
{
return [
'id' => ['required', 'exists:invites,id,status,pending']
];
}
to make sure record you edit has status pending
. 确保您编辑的记录的状态为pending
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.