Create Select Options from Enums, Laravel Models, and more


July 15th, 2022

Create Select Options from Enums, Laravel Models, and more

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';
/* returns the following array
['label' => 'Frodo', 'value' => 'frodo'],
['label' => 'Sam', 'value' => 'sam'],
['label' => 'Merry', 'value' => 'merry'],
['label' => 'Pippin', 'value' => 'pippin'],
// Or return JSON

Not only can you use Enums, but this package also supports data from various sources, including:

Another neat feature is that you can turn your options into a validation rule:

// ['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.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.