How command dependencies work
2.0Commands can require user input through dependencies. This is handled by defining a dependencies() method that returns a SpotlightCommandDependencies collection.
Defining Dependencies
Use SpotlightCommandDependencies::collection() and SpotlightCommandDependency::make() to register dependencies. You can set placeholders and specify if a dependency is a standard input using setType(SpotlightCommandDependency::INPUT).
Implementing Search for Dependencies
For every dependency registered, Spotlight looks for a method named search{dependency-name} on your command class. This method must return a collection of SpotlightSearchResult objects.
SpotlightSearchResult structure:
- Identifier (ID)
- Name
- Description
Scoped Dependency Searching
Dependency search methods have access to previously resolved dependencies. For example, if team is the first dependency and foobar is the second, searchFoobar($query, Team $team) can use the $team object to scope its search.
use LivewireUI\Spotlight\Spotlight;
use LivewireUI\Spotlight\SpotlightCommand;
use LivewireUI\Spotlight\SpotlightCommandDependencies;
use LivewireUI\Spotlight\SpotlightCommandDependency;
use LivewireUI\Spotlight\SpotlightSearchResult;
class CreateUser extends SpotlightCommand
{
public function dependencies(): ?SpotlightCommandDependencies
{
return SpotlightCommandDependencies::collection()
->add(SpotlightCommandDependency::make('team')->setPlaceholder('For which team?'))
->add(SpotlightCommandDependency::make('foobar')->setType(SpotlightCommandDependency::INPUT));
}
public function searchTeam($query)
{
return Team::where('name', 'like', "%$query%")
->get()
->map(fn($team) => new SpotlightSearchResult($team->id, $team->name, "Create user for {$team->name}"));
}
public function searchFoobar($query, Team $team)
{
// $team is available here because it was defined earlier in the dependencies list
}
public function execute(Spotlight $spotlight, Team $team, string $foobar): void
{
// ...
}
}