Custom datetime filter within relation

I am building a table for an Alert model, whose timestamp is found through a 'timestamp' column from a related model (event), and I'm trying to get a filter on that, like this:
Filter::make('event.timestamp')
->form([
DateTimePicker::make('event.time_from')
->seconds(false),
DateTimePicker::make('event.time_until')
->seconds(false),
])
->query(function (Builder $query, array $data): Builder {
return $query
->when(
$data['time_from'],
fn (Builder $query, $date): Builder => $query->whereDate('timestamp', '>=', $date),
)
->when(
$data['time_until'],
fn (Builder $query, $date): Builder => $query->whereDate('timestamp', '<=', $date),
);
})
Filter::make('event.timestamp')
->form([
DateTimePicker::make('event.time_from')
->seconds(false),
DateTimePicker::make('event.time_until')
->seconds(false),
])
->query(function (Builder $query, array $data): Builder {
return $query
->when(
$data['time_from'],
fn (Builder $query, $date): Builder => $query->whereDate('timestamp', '>=', $date),
)
->when(
$data['time_until'],
fn (Builder $query, $date): Builder => $query->whereDate('timestamp', '<=', $date),
);
})
However, I get an error pointing 'time_from' and 'time_until' indexes do not exist in $data, which seems correct since $data is completely empty. What I'm missing in between? Why is $data empty?
Solution:
Okey, I just solved it easily by using whereHas on QueryBuilder ```php Filter::make('timestamp') ->form([ DateTimePicker::make('time_from')...
Jump to solution
1 Reply
Solution
titoshadow
titoshadow5mo ago
Okey, I just solved it easily by using whereHas on QueryBuilder
Filter::make('timestamp')
->form([
DateTimePicker::make('time_from')
->seconds(false),
DateTimePicker::make('time_until')
->seconds(false),
])
->query(function (Builder $query, array $data): Builder {
return $query
->when(
$data['time_from'],
fn(Builder $query, $date): Builder => $query->whereHas('event', function ($event) use ($date) {
$event->whereDate('timestamp', '>=', $date);
}),
)
->when(
$data['time_until'],
fn(Builder $query, $date): Builder => $query->whereHas('event', function ($event) use ($date) {
$event->whereDate('timestamp', '<=', $date);
}),
);
})
Filter::make('timestamp')
->form([
DateTimePicker::make('time_from')
->seconds(false),
DateTimePicker::make('time_until')
->seconds(false),
])
->query(function (Builder $query, array $data): Builder {
return $query
->when(
$data['time_from'],
fn(Builder $query, $date): Builder => $query->whereHas('event', function ($event) use ($date) {
$event->whereDate('timestamp', '>=', $date);
}),
)
->when(
$data['time_until'],
fn(Builder $query, $date): Builder => $query->whereHas('event', function ($event) use ($date) {
$event->whereDate('timestamp', '<=', $date);
}),
);
})
Although I feel like there should be (or there actually is) a better way to do this
Want results from more Discord servers?
Add your server