Blog Detail


Create Lists of Options from Different Sources in Laravel cover image

arrow_back Create Lists of Options from Different Sources in Laravel

Spatie has created a new package called spatie/laravel-options. It will take a resource that 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. A typical web application always has many select fields with options. This package makes it simple to transform enums, models, states, and arrays into a unified option structure.


You can install the package via composer:

composer require spatie/laravel-options


You can create an Options object like this (we’ll cover other things then enums later on):


You can get an array representation of the options like this:


Or a JSON version like this:


You can return options as part of a response in your controller, and they will be automatically converted into JSON:

class ShowHobbitsController{
    public function __invoke(RingBearer $ringBearer){
        return [
            'ring_bearer' => $ringBearer,
            'hobbit_options' => Options::forEnum(Hobbit::class)

Manipulating options

You can sort options by their label like this:


Or use a closure to sort the options:

Options::forEnum(Hobbit::class)->sort(fn(Hobbit $hobbit) => $hobbit->value);

You can append additional data to the options like this:

Options::forEnum(Hobbit::class)->append(fn(Hobbit $hobbit) => [
    'ring_bearer' => $hobbit === Hobbit::Frodo || $hobbit === Hobbit::Sam

This will result in the following options array:

    ['label' => 'Frodo', 'value' => 'frodo', 'ring_bearer' => true],
    ['label' => 'Sam', 'value' => 'sam', 'ring_bearer' => true],
    ['label' => 'Merry', 'value' => 'merry', 'ring_bearer' => false],
    ['label' => 'Pippin', 'value' => 'pippin', 'ring_bearer' => false],

With Enums

You can create options for native PHP enums, Spatie Enums, and MyClabs Enums like this:


With Models

You can create options for Laravel models like this:


Use a single model like this:


This package has a lot of other options and features, If you want to know more, you can visit its complete documentation on Github.

Published at : 15-07-2022

Author : Rizwan Aslam
Rizwan Aslam

I am a highly results-driven professional with 12+ years of collective experience in the grounds of web application development especially in laravel, native android application development in java, and desktop application development in the dot net framework. Now managing a team of expert developers at Codebrisk.

Launch your project

Launch project