Free·

Preserve the selected tab after a page refresh

Preserve the selected tab after a page refresh

Working with multiple tabs in your Filament ListPage and want to keep the selected tab active even after a refresh? Here's a clean solution using session state.

The trick

Just override the mount() and updatedActiveTab() methods in your ListRecords page like this:

app/Filament/Resources/Posts/Pages/ListPosts.php
<?php

namespace App\Filament\Resources\Posts\Pages;

use App\Enums\PostStatus;
use App\Filament\Resources\Posts\PostResource;
use Filament\Actions\CreateAction;
use Filament\Resources\Pages\ListRecords;
use Filament\Schemas\Components\Tabs\Tab;
use Filament\Support\Icons\Heroicon;
use Illuminate\Database\Eloquent\Builder;

class ListPosts extends ListRecords
{
    protected static string $resource = PostResource::class;

    public function mount(): void
    {
        parent::mount();

        $this->activeTab = session('postActiveTab', $this->getDefaultActiveTab());
    }

    public function updatedActiveTab(): void
    {
        parent::updatedActiveTab();
        session(['postActiveTab' => $this->activeTab]);
    }

    public function getTabs(): array
    {
        return [
            'all' => Tab::make()
                ->icon(Heroicon::OutlinedQueueList),

            'draft' => Tab::make()
                ->icon(PostStatus::Draft->getIcon())
                ->modifyQueryUsing(fn (Builder $query) => $query->whereStatus(PostStatus::Draft)),

            'published' => Tab::make()
                ->icon(PostStatus::Published->getIcon())
                ->modifyQueryUsing(fn (Builder $query) => $query->whereStatus(PostStatus::Published)),

            'archived' => Tab::make()
                ->icon(PostStatus::Archived->getIcon())
                ->modifyQueryUsing(fn (Builder $query) => $query->whereStatus(PostStatus::Archived)),
        ];
    }

    protected function getHeaderActions(): array
    {
        return [
            CreateAction::make(),
        ];
    }
}

Now when users select a tab like Published, that tab will stay active even after they refresh the page or change to another page.

Conclusion

Simple UX boost. No extra packages. All native Filament 😉

Download source code

Download on GitHub

Join the Discussion

Run project on Firebase Studio

  • Open studio.firebase.google.com and import the repository https://github.com/wiremodel/simple-blog
  • Run the project. Once it's up, switch to the correct branch:
git checkout v4/preserve-selected-tab

Update dependencies and migrate the database:

composer update -W
php artisan migrate:fresh --seed
Make sure your .env file has APP_URL set to the URL provided by Firebase Studio.