Laravel Options by Spatie is a package to create lists of options from different sources:
A typical web application always has many select fields with options. This package makes it simple to transform enums, models, states, and arrays to a unified option structure.
An example from the readme illustrates how this package can help ease working with select options in Laravel applications. Given an enum, you can use this package to build options:
1enum Hobbit: string 2{ 3 case Frodo = 'frodo'; 4 case Sam = 'sam'; 5 case Merry = 'merry'; 6 case Pippin = 'pippin'; 7} 8 9Options::forEnum(Hobbit::class)->toArray();10 11/* returns the following array12[13 ['label' => 'Frodo', 'value' => 'frodo'],14 ['label' => 'Sam', 'value' => 'sam'],15 ['label' => 'Merry', 'value' => 'merry'],16 ['label' => 'Pippin', 'value' => 'pippin'],17]18*/19 20// Or return JSON21Options::forEnum(Hobbit::class)->toJson();
Not only can you use Enums, but this package also supports data from various sources, including:
- Models
- Model States (via Spatie Model States)
- Arrays
- Manually
Another neat feature is that you can turn your options into a validation rule:
1$request->validate([2 // ['in:frodo,sam,merry,pippin']3 'hobbit' => Options::forEnum(Hobbit::class)->toValidationRule()4]);
You can learn more about this package, get full installation instructions, and view the source code on GitHub. Also, read Introducing our new Laravel Options package by Freek Van der Herten to get the background and details on this package.