15
JulSpatie 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.
You can install the package via composer:
composer require spatie/laravel-options
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)
]
}
}
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],
]
You can create options for native PHP enums, Spatie Enums, and MyClabs
Enums like this:
Options::forEnum(Hobbit::class);
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.
Published at : 15-07-2022
I am a highly results-driven professional with 12+ years of collective experience in the grounds of web application development especially in laravel, native android application development in java, and desktop application development in the dot net framework. Now managing a team of expert developers at Codebrisk.
Launch project