Reputation: 971
My function store() works, but I dont' know how to adapt in my method update() ??
$conflictTraining = Training::where('fk_motorbike', $request->get('fk_motorbike'))
->whereDate('date_seance', "=" , $date_revision_start)
->where('hour_start', "<=" , $request->get('hour_start'))
->where('hour_end', ">=" , $request->get('hour_end'))
->first();
$conflictTraining2 = Training::where('fk_motorbike', $request->get('fk_motorbike'))
->whereDate('date_seance', "=" , $date_revision_end)
->where('hour_start', "<=" , $request->get('hour_start'))
->where('hour_end', ">=" , $request->get('hour_end'))
->first();
Here is an idea of my function update(), but it's doesn't good...
$conflictTraining = Training::where('id', '!=', $id)
->where('fk_motorbike', $request->get('fk_motorbike'))
->whereDate('date_seance', "=" , $date_revision_start)
->where('hour_start', "<=" , $request->get('hour_start'))
->first();
$conflictTraining2 = Training::where('fk_motorbike', $request->get('fk_motorbike'))
->whereDate('date_seance', "=" , $date_revision_end)
->where('hour_end', ">=" , $request->get('hour_end'))
->first();
if( (isset($conflictTraining2) && $conflictTraining2->id !== intval($id))
|| (isset($conflictTraining) && $conflictTraining->id !== intval($id)) ){
return redirect()->route('revisions.index')
->with('error', 'date duplicate ');
}
Upvotes: 0
Views: 90
Reputation: 757
I did face similar issue trying to solve time intersection, and I used datetime instead of just time to store interval.
To solve that, two methods were created, one to check internal period conflict and another to check external period conflict.
First, I suggest you to change your fields start_hour
and end_hour
to start_time
and end_time
, respectively, both datetime type.
Here a model sample with these methods
class Training extends Model
{
protected $fillable = [
'start_time',
'end_time'
];
public function isValidOrFail()
{
$collection = $this->all();
$collection->each(function ($current) {
if($current->start_time and $current->end_time) {
if($this->hasConflictWithInternalPeriod($current) or $this->hasConflictWithExternalPeriod($current)) {
throw new InvalidPeriodException("Here my exception message");
}
}
});
return true;
}
protected function hasConflictWithInternalPeriod($training)
{
return $this->start_time->between($training->start_time, $training->end_time)
or $this->end_time->between($training->start_time, $training->end_time);
}
protected function hasConflictWithExternalPeriod($training)
{
return $training->start_time->between($this->start_time, $this->end_time
or $training->end_time->between($this->start_time, $this->end_time);
}
}
This may sounds a lot different of what you are expecting, but I hope it helps you.
You call method isValidOrFail()
, it will check current model against all other records, validating internal and external period conflict.
Upvotes: 1