How to set the correct default value and labels for Laravel Nova Select dropdowns

Background

Enumerated types are useful when programming user interfaces because they allow you to de-couple some logic away from front-end. In this article we’re trying to solve a common UI problem whereby a default value must be selected for a Select dropdown when the user lands on the page.
For the purposes of the example we’re working with a Tasks table that can four statuses, namely New, In Progress, On Hold, and Done.
Our design objectives are:
1. Set a default value “New” when the user lands on the page to create a new record
2. Ensure that the database values for Status are consistent, and in lowercase with underscores
3. Ensure that the labels in the Dropdown are displayed in plain english
The enumerated class looks like this:
<?php

namespace App\Enums;

class Tasks
{

    const NEW         = "new";
    const IN_PROGRESS = "in_progress";
    const ON_HOLD     = "on_hold";    
    const COMPLETED   = "completed";    

    public static function uiOptions()
    {
        return [
            self::NEW         => 'New',
            self::IN_PROGRESS => 'In Progress',
            self::ON_HOLD     => 'On Hold',
            self::COMPLETED   => 'Completed',            
        ];
    }

}
The Tasks ‘enum’ class allows us to specify fixed values for the database, whilst having easy to access static constants for manipulation in our code or the user interface. Essentially this design allow to avoid constructs like this:
if ($status == 'New') { } // Avoid putting in hardcoded values in your code
When creating the Select dropdown in Laravel Nova, we can now use some of it’s advanced functionality to set the default value, display proper labels, and even allow sorting by value.
Select::make('Status')->options(
    Leads::uiOptions())
        ->displayUsingLabels(),
        ->resolveUsing(function () {
            return $this->status ?? Leads::NEW;
        })
        ->sortable()
In the above example resolveUsing is key to solving the problem with setting the correct default.
Setting defaults on a Laravel Nova application can be a bit of a challenge, but additions such resolveUsing allows us to do almost anything imaginable on our beautiful front-ends.
For more information on the challenges of setting Laravel Nova resource field defaults, see this GitHub issue.
Please note, as per the GitHub post, with other input types it’s probably easier to just use withMeta if you want to set a default. In my experience withMeta and Selects don’t work perfectly together unless your UI’s value’s spelling is the same as your stored database value.
Let us know in the comments if you’ve had to solve a particular challenging Laravel Nova front-end default issue.

 

Share this article

1 thought on “How to set the correct default value and labels for Laravel Nova Select dropdowns”

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to Top