Create Select Options from Enums, Laravel Models, and more
Published on by Paul Redmond
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:
enum Hobbit: string{ case Frodo = 'frodo'; case Sam = 'sam'; case Merry = 'merry'; case Pippin = 'pippin';} Options::forEnum(Hobbit::class)->toArray(); /* returns the following array[ ['label' => 'Frodo', 'value' => 'frodo'], ['label' => 'Sam', 'value' => 'sam'], ['label' => 'Merry', 'value' => 'merry'], ['label' => 'Pippin', 'value' => 'pippin'],]*/ // Or return JSONOptions::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:
$request->validate([ // ['in:frodo,sam,merry,pippin'] 'hobbit' => Options::forEnum(Hobbit::class)->toValidationRule()]);
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.