Laravel-更新日期的验证规则 [英] Laravel - validation rule for date on update
问题描述
我有此验证规则:
'event_start' => 'required|date|after:today',
在创建模型时一切都很好,这个日期不能早于今天....
and on creating a model all is fine, this date cannot be before today....
但是当用户尝试更新事件的开始日期是今天之前,并且弹出验证错误....是否可以通过调整方法来更新模型?这样,当用户更新此规则时,仅检查是否是日期?
but when a user tries to update the event start date is before today and a validation error pops up....is there a way to adjust this for updating the model? So that when a user updates this rule checks only if it is a date?
更新
这是我对创建和更新的唯一验证检查:
this is my only validation check for both create and update:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class EventsForm extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
if( auth()->check() )
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
$rules = [
'title' => 'required|min:2|max:255',
'event_start' => 'required|date|after:today',
];
return $rules;
}
}
推荐答案
您应该具有用于创建和更新事件的不同表单请求类.但这并不是说您不能使用继承.
You should have different form request classes for creating and updating events. That’s not to say you can’t use inheritance, though.
如果您的更新方法仅与创建方法不同,那么您可以扩展该方法的表单请求并修改更新规则:
If your update method only slightly differs from the create method, then you could extend that method’s form request and amend the rules for update:
class CreateEventRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'name' => 'required|unique:events',
'start_date' => 'required|date|after:today',
'door_time' => 'required|date_format:"H:i:s",
'location' => 'required',
];
}
}
然后……
class UpdateEventRequest extends CreateEventRequest
{
public function rules()
{
// Get ID of event if using route–model binding
$id = $this->route('event')->getKey();
// Use array merge to override create event form request’s rules
return array_merge(parent::rules(), [
'name' => 'required|unique:events,name,'.$id,
'start_date' => 'required|date',
]);
}
}
您甚至可以将rules方法推送到抽象类,并让您的创建和更新表单请求类扩展 that 类:
You could even push the rules method to an abstract class, and have your create and update form request classes extend that class:
abstract class EventFormRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
// Base event rules
}
}
class CreateEventRequest extends EventFormRequest
{
public function rules()
{
// Create-specific rules
}
}
class UpdateEventRequest extends EventFormRequest
{
public function rules()
{
// Update-specific rules
}
}
这篇关于Laravel-更新日期的验证规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!