Spatie has created a new package called spatie/laravel-options. It will take a resource that can create options such as an enum, a list of models, or even a plain array. And will always create a standardized array of options you can use within your frontend application. A typical web application always has many select fields with options. This package makes it simple to transform enums, models, states, and arrays into a unified option structure.
Installation
You can install the package via composer:
composer require spatie/laravel-options
Usage
You can create an Options object like this (we’ll cover other things then enums later on):
Options::forEnum(Hobbit::class);
You can get an array representation of the options like this:
Options::forEnum(Hobbit::class)->toArray();
Or a JSON version like this:
Options::forEnum(Hobbit::class)->toJson();
You can return options as part of a response in your controller, and they will be automatically converted into JSON:
class ShowHobbitsController{
public function __invoke(RingBearer $ringBearer){
return [
'ring_bearer' => $ringBearer,
'hobbit_options' => Options::forEnum(Hobbit::class)
]
}
}
Manipulating options
You can sort options by their label like this:
Options::forEnum(Hobbit::class)->sort();
Or use a closure to sort the options:
Options::forEnum(Hobbit::class)->sort(fn(Hobbit $hobbit) => $hobbit->value);
You can append additional data to the options like this:
Options::forEnum(Hobbit::class)->append(fn(Hobbit $hobbit) => [
'ring_bearer' => $hobbit === Hobbit::Frodo || $hobbit === Hobbit::Sam
]);
This will result in the following options array:
[
['label' => 'Frodo', 'value' => 'frodo', 'ring_bearer' => true],
['label' => 'Sam', 'value' => 'sam', 'ring_bearer' => true],
['label' => 'Merry', 'value' => 'merry', 'ring_bearer' => false],
['label' => 'Pippin', 'value' => 'pippin', 'ring_bearer' => false],
]
With Enums
You can create options for native PHP enums, Spatie Enums, and MyClabs Enums like this:
Options::forEnum(Hobbit::class);
With Models
You can create options for Laravel models like this:
Options::forModels(Wizard::class);
Use a single model like this:
Options::forModels(Wizard::first());
This package has a lot of other options and features, If you want to know more, you can visit its complete documentation on Github.