My project is to create a small driving school for motorbike.
I have 4 tables: Former, Training, Revision, Motorbike
My functions cre
This is possible, and you have almost got what you need already. You can model the training duplicate code after the duplicate revision code and add a very similar revision duplicate code to get your answer.
I am going to explain in detail and repeat myself codewise, but hopefully this will be easier to understand. You can compress this code once it makes sense to you. Not the least of which would be to make the duplicate code for revision a separate method within your Controller Revision, so that both Controller Revision and Controller Training can draw from it. But that's later - for now let's get it working.
On your Controller Training, remove the $exists
stuff for now. First we need to make sure there is no revision at the same time as the user wants to apply training for the motorbike. In this case, though, there is only one date for Training in your model, so only one $conflict
check for the revision:
$date_start = $request->get('date_seance'); // I assume your form field for training is date_seance
$fk_motorbike = $request->get('fk_motorbike');
// NOTE: the $date_start MAY need to be converted to a Carbon instance if it doesn't work - same as before
$conflictRevision = Revision::where('fk_motorbike', $fk_motorbike)
->whereDate('date_revision_start', "<=" , $date_start)
->whereDate('date_revision_end', ">=", $date_start)
->first();
Now we need to check to see if there is a conflict for training. We can use the same PHP variables already assigned, just change the model we are querying. I assume seance is ONE day per your model:
$conflictTraining = Training::where('fk_motorbike', $fk_motorbike)
->whereDate('date_seance', "=" , $date_start)
->first();
And then it is a very similar if-check to the one we used in the revision check:
if(isset($conflictTraining) || isset($conflictRevision)){
return redirect()->route('trainings.index')
->with('error', 'Duplicate ');
else{
Training::create($request->all());
return redirect()->route('trainings.index')
->with('success', 'Add');
}
The easiest way is making use of a query scope in the Training model. I'll assume that a motorbike is the whole day unavailable when in revision.
public function scopeAvailable($query)
{
return $query->whereNotBetween('trainings.date_sceance', [
'revisions.date_revision_start' => function($q) {
return $q->where('trainings.fk_motorbike', '=', 'revisions.fk_motorbike');
},
'revisions.date_revision_end' => function($q) {
return $q->where('trainings.fk_motorbike', '=', 'revisions.fk_motorbike');
}]
);
}
I haven't test this code. It is possible it won't give what you expect, in other words, my proposition is wrong. Using the scope would be
$exists = Training::where('date_seance', $request->get('date_seance'))->available()->count();