Courses

Laravel Filament Admin v2: Practical Course

Date Filters for Payment From/Until

Previous: Generate Resource and Disable Create/Edit/Delete
avatar

I'm having problems with the DatePicker because by default it fills the created_from and created_until fields with the current date, so the list appears empty because these filters are applied.

I've seen that you can pass a default value to DatePicker and then the page will load with those values, but it will not accept the value null so it will always appear filtered by default.

I have consulted the current official documentation with the same use case and I can't get it to work as expected either.

:(

avatar

What are you trying to achieve? Filters aren't set when you visit the page first time

avatar

It is just the opposite, when I visit the page for the first time it appears filtered with the date created_from and created_until with today's date, and as there is no record that matches those values the table appears empty until you click on the filters and reset them. I wonder why this happens, I have checked the code thoroughly and I can't get the created_from and created_until values to appear empty when loading the page for the first time.

Here is my code updated with the official documentation of the moment about this particular section:

use Filament\Tables\Filters\Filter;
use Illuminate\Database\Eloquent\Builder;
use Filament\Forms\Components\DatePicker;
use Illuminate\Support\Carbon;

            ->filters([
                Filter::make('created_at')
                    ->form([
                        DatePicker::make('created_from')->default(Carbon::now()->startOfYear()),
                        DatePicker::make('created_until'),
                    ])
                    ->query(function (Builder $query, array $data): Builder {
                        return $query
                            ->when(
                                $data['created_from'],
                                fn (Builder $query, $date): Builder => $query->whereDate('created_at', '>=', $date)
                            )->when(
                                $data['created_until'],
                                fn (Builder $query, $date): Builder => $query->whereDate('created_at', '<=', $date)
                            );
                    }),
            ])

For the moment, as a temporary solution, I am making it load with the records from the beginning of the year, so the list does not appear empty.

avatar

Just added your filter into table and it works as expected. When I visit page first time all records are shown and when I select created_from only then filter is applied.

avatar

That code works because I set the default created_from value at the beginning of the year, if you remove the default method from the DatePicker does it work the same?

avatar

Sorry, forgot to mention, I removed the default from your filter code.

avatar
You can use Markdown
avatar
You can use Markdown