Skip to content

Custom Queries

If you want to search for specific data in your Panel you can create custom queries. Every query extends the SpotlightQuery class and can be configured via the setUp() method. A simple query could be a search for a specific user.

Usually you want your queries to be scoped by a Context to only show up in the right place. You can do this by using the forContext() method.

A query can must return a Illuminate\Support\Collection of SpotlightResult objects.

php
use pxlrbt\FilamentSpotlightPro\SpotlightContext;
use pxlrbt\FilamentSpotlightPro\SpotlightQueries\SpotlightQuery;
use pxlrbt\FilamentSpotlightPro\SpotlightResults\SpotlightResult;

class AdminUsersQuery extends SpotlightQuery
{
    public function setUp(): void
    {
        $this->query(function (string $search, SpotlightContext $context) {            
            return User::query()
                ->where('role', 'admin')
                ->where('name', 'like', "%{$search}%")
                ->map(function ($user) {
                    return SpotlightResult::make()
                        ->label($user->name)
                        ->icon('heroicon-o-user')
                        ->url(UserResource::getUrl('view') ['record' => $user]));
                });
                ->get();
        });        
    }
}

Context

Again you can use the context for another level of filtering and showing more options instead of linkin to a result directly:

php
use pxlrbt\FilamentSpotlightPro\SpotlightContext;
use pxlrbt\FilamentSpotlightPro\SpotlightQueries\SpotlightQuery;
use pxlrbt\FilamentSpotlightPro\SpotlightResults\SpotlightResult;

class AdminUsersQuery extends SpotlightQuery
{
    public function setUp(): void
    {
        $this->query(function (string $search, SpotlightContext $context) {            
            return User::query()
                ->where('role', 'admin')
                ->where('name', 'like', "%{$search}%")
                ->limit(15)
                ->map(function ($user) {
                    return SpotlightResult::make()
                        ->label($user->name)
                        ->icon('heroicon-o-user')
                        ->action(
                            PushContextAction::make('user')->data(['user' => $user->id])
                        )
                });
                ->get();
        });        
    }
}

You can than add more commands for the user context by using ->forContext('/user').

Preloading

You can also preload queries to show results directly when opening Spotlight. By default queries are not preloaded to keep performance up. You can change this by using ->preload(true). Make sure to limit your results to a reasonable amount.