Introducing our new Laravel Options package
When developing web applications, you probably encounter a lot of places where someone needs to select one or more options in a select or multi-select. These select boxes always need a list of options with labels and values.
In one of our projects, we had options being generated in lots of places. Sometimes these lists of options were the same, leading to a lot of code duplication. Even worse, in some cases, different formats were used to output the same options.
That's why we've created a new package called spatie/laravel-options. It will take a resource which 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.
For example, let's say you have an enum like this:
enum Hobbit: string
{
case Frodo = 'frodo';
case Sam = 'sam';
case Merry = 'merry';
case Pippin = 'pippin';
}
You can easily convert this to a list of options like this:
Options::forEnum(Hobbit::class)->toArray();
Which will return the following array:
[
['label' => 'Frodo', 'value' => 'frodo'],
['label' => 'Sam', 'value' => 'sam'],
['label' => 'Merry', 'value' => 'merry'],
['label' => 'Pippin', 'value' => 'pippin'],
]
You can create options from a model like this:
Options::forModels(Wizard::class);
Or from a query which returns models:
Options::forModels(Wizard::query()->where('name', 'gandalf'));
And even a plain array can be used to create options:
Options::forArray([
'gondor' => 'Gondor',
'rohan' => 'Rohan',
'mordor' => 'Mordor',
])
Before sending the options to the front, you can change how they will be created. For example, you could sort them:
Options::forEnum(Hobbit::class)->sort();
Or filter out specific options:
Options::forEnum(Hobbit::class)->filter(fn(Hobbit $hobbit) => $hobbit === Hobbit::Frodo);
Add an empty option, which will have a null
value:
Options::forEnum(Hobbit::class)->nullable();
Or append extra data properties to the options:
Options::forEnum(Hobbit::class)->append(fn(Hobbit $hobbit) => [
'ring_bearer' => $hobbit === Hobbit::Frodo || $hobbit === Hobbit::Sam
]);
You can read more about creating options from resources, how to manipulate them and how to change the label and value of the options in the docs.
If you like our open source work, consider picking up one of our paid products or premium video courses.
Great new package