• Reading time ~ 1 min
  • 10.08.2022

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 JSON
Options::forEnum(Hobbit::class)->toJson();

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:

$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.

Comments

No comments yet
Yurij Finiv

Yurij Finiv

Full stack

ABOUT

Professional Fullstack Developer with extensive experience in website and desktop application development. Proficient in a wide range of tools and technologies, including Bootstrap, Tailwind, HTML5, CSS3, PUG, JavaScript, Alpine.js, jQuery, PHP, MODX, and Node.js. Skilled in website development using Symfony, MODX, and Laravel. Experience: Contributed to the development and translation of MODX3 i...

About author CrazyBoy49z
WORK EXPERIENCE
Contact
Ukraine, Lutsk
+380979856297