use Carbon\CarbonPeriod;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
class EnrollRequest extends FormRequest
{
protected $stopOnFirstFailure = true;
public function rules(): array
{
return [
'courses' => ['required', 'array'],
'courses.*' => ['required', 'exists:courses,id'],
];
}
public function withValidator(Validator $validator): void
{
$user_courses = $this->user()->courses;
$validator->after(function (Validator $validator) use ($user_courses) {
$data = $validator->getData();
$courses = Course::whereIn('id', $data['courses'])->get();
foreach ($courses as $i => $course) {
// check user hasn't enrolled in the course already
if ($user_courses->contains($course) {
$validator->errors()->add("courses.$i", 'User is already enrolled in this course.');
}
// check if the course doesn't overlap with other courses the user has
$course_period = CarbonPeriod::create($course->start_date, $course->end_date);
foreach ($user_courses as $user_course) {
if ($couse_period->overlaps($user_course->start_date, $user_course->end_date)) {
$validator->errors()->add("courses.$i", 'Course overlaps.');
}
}
}
});
}
}
// controller
public function enroll(EnrollRequest $request)
{
$request->user()->courses()->attach($request->validated()['courses']);
}
单课程
use Carbon\CarbonPeriod;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
class EnrollRequest extends FormRequest
{
protected $stopOnFirstFailure = true;
public function rules(): array
{
return [
'course_id' => ['required', 'exists:courses,id'],
];
}
public function withValidator(Validator $validator): void
{
$user_courses = $this->user()->courses;
$validator->after(function (Validator $validator) use ($user_courses) {
$data = $validator->getData();
$course = Course::find($data['course_id']);
// check user hasn't enrolled in the course already
if ($user_courses->contains($course) {
$validator->errors()->add("courses.$i", 'User is already enrolled in this course.');
}
// check if the course doesn't overlap with other courses the user has
$course_period = CarbonPeriod::create($course->start_date, $course->end_date);
foreach ($user_courses as $user_course) {
if ($couse_period->overlaps($user_course->start_date, $user_course->end_date)) {
$validator->errors()->add('course_id', 'Course overlaps.');
}
}
});
}
}
// controller
public function enroll(EnrollRequest $request)
{
$request->user()->courses()->attach($request->validated()['course_id']);
}
1条答案
按热度按时间fxnxkyjh1#
您可以在表单请求中使用自定义验证规则来验证它。
要检查课程周期是否重叠,使用
CarbonPeriod
的overlaps
方法非常简单。因为我想不出有什么验证规则可以立即执行此操作,所以我使用验证器的
after
来注册一个回调方法。多课程:
单课程