Custom Filter for Date in Relationship not working properly

Hello, I am trying to filter the records as per the date field in the relationship (belongsTo), which filters wrong records. Booking Model - Relationship:
public function trainingEvent()
{
return $this->belongsTo(TrainingEvent::class, 'training_id');
}
public function trainingEvent()
{
return $this->belongsTo(TrainingEvent::class, 'training_id');
}
Booking Resource Filter:
Filter::make('training_date')
->form([
DatePicker::make('start_from')->native(false)->format('Y-m-d')->displayFormat('d/m/Y'),
DatePicker::make('start_until')->native(false)->format('Y-m-d')->displayFormat('d/m/Y'),
])
->query(function (Builder $query, array $data): Builder {
return $query->whereHas('trainingEvent', function (Builder $query) use ($data) {
if (!empty($data['start_from']) && !empty($data['start_until'])) {
$startDate = Carbon::parse($data['start_from'])->startOfDay();
$endDate = Carbon::parse($data['start_until'])->endOfDay();

$query->whereBetween('start_date', [$startDate, $endDate]);
} elseif (!empty($data['start_from'])) {
$startDate = Carbon::parse($data['start_from'])->startOfDay();

$query->where('start_date', '>=', $startDate);
} elseif (!empty($data['start_until'])) {
$endDate = Carbon::parse($data['start_until'])->endOfDay();

$query->where('start_date', '<=', $endDate);
}
});
}),
Filter::make('training_date')
->form([
DatePicker::make('start_from')->native(false)->format('Y-m-d')->displayFormat('d/m/Y'),
DatePicker::make('start_until')->native(false)->format('Y-m-d')->displayFormat('d/m/Y'),
])
->query(function (Builder $query, array $data): Builder {
return $query->whereHas('trainingEvent', function (Builder $query) use ($data) {
if (!empty($data['start_from']) && !empty($data['start_until'])) {
$startDate = Carbon::parse($data['start_from'])->startOfDay();
$endDate = Carbon::parse($data['start_until'])->endOfDay();

$query->whereBetween('start_date', [$startDate, $endDate]);
} elseif (!empty($data['start_from'])) {
$startDate = Carbon::parse($data['start_from'])->startOfDay();

$query->where('start_date', '>=', $startDate);
} elseif (!empty($data['start_until'])) {
$endDate = Carbon::parse($data['start_until'])->endOfDay();

$query->where('start_date', '<=', $endDate);
}
});
}),
Result: (attached) I want to filter the results where start_date from trainingEvent relationship is between 08/08/2024 to 09/08/2024 but it also includes the records from the month of July. Please help me understand if i am doing anything wrong in this.
No description
0 Replies
No replies yetBe the first to reply to this messageJoin
Want results from more Discord servers?
Add your server