Eloquent, Laravel

Laravel: Generic Select Options Populator

Assalamualaikum / Hi,

Just a quick share how I generate select options from the given Eloquent model. Assuming you have a model called `App\Models\Country` and you want to get the list of country as select options.

Of course you will go query from eloquent and do the mapping to set the value and label for the options.

In that case, I have a helper:

This helper, allow me to generate the select options based on given model name, key and value want to populate.

Let say you have list of Country, you can use above helper to generate the select options:

selectOptions('\App\Models\Country::class, 'country', 'country');

Above codes will simply return an array:

[
"Malaysia" => "Malaysia",
...
]

If you are using Laravel Nova:

Select::make(__('Country'), 'country')->options(
selectOptions(\App\Models\Country::class, 'country', 'country')
)->onlyOnForms()->displayUsingLabels(),

And would return the following in Nova:

Hope this small code snippet help you on your projects!

Thanks,
Nasrul Hazim

Leave a Reply

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

three × two =