FilamentLaravel

      Filament PHP: How to Globally Configure Default Table Sorting

      If you are working with Filament PHP, you’ve likely noticed that you often repeat the same configurations across various Resource tables. One of the most common requirements is sorting—for instance, ensuring that the latest records (by ID) always appear at the top of the list.

      Instead of manually adding ->defaultSort('id', 'desc') to every single resource, there is a much more elegant and “clean” way to handle this: Global Configuration.

      The Problem: Code Duplication (WET Code)

      Imagine your project grows to 10 or 20 resources: Countries, Cities, Users, Addresses, and more. Writing the same line of code in every single file violates the DRY (Don’t Repeat Yourself) principle. In professional development, if something repeats consistently, it should be centralized.

      The Solution: AppServiceProvider

      Filament provides a powerful way to “hook” into the table-building process globally. The ideal place for this is the AppServiceProvider.php file.

      Open app/Providers/AppServiceProvider.php and add the following code inside the boot method:

      PHP

      use Filament\Tables\Table;
      
      /**
       * Bootstrap any application services.
       */
      public function boot(): void
      {
          Table::configureUsing(function (Table $table): void {
              $table->defaultSort('id', 'desc');
          });
      }
      

      Why This Approach Works Best

      1. Centralized Management: If you decide tomorrow that you’d prefer sorting by created_at instead of id, you only change it in one file, and the change reflects across your entire application.
      2. Clean Resources: Your Resource files (Resource.php) become smaller, cleaner, and easier to read.
      3. Local Priority (Overrides): If a specific resource (e.g., CategoryResource) requires a different sorting logic (like alphabetical order), simply adding ->defaultSort() inside that specific resource will override the global setting. Local configurations always take precedence.

      One Important Detail

      Keep in mind that this global rule assumes all your models have an id column. If you have a table with a different Primary Key name, you should manually specify the sorting for that specific resource to avoid SQL “column not found” errors.

      Summary

      Small optimizations like this separate a basic project from a professionally architected system. The less boilerplate code we write, the lower the chance of making a mistake.

      Hi, I’m elliotkartvel