Skip to content
The Web Fosters: ideas into reality
Menu

Adding custom attributes to Select field in laravelcollective HTML

31 October 2017, by Nikhil Agrawal

Written in 2017. Versions and links mentioned here may be out of date.

Most of the time we use HTML select without any custom attributes. But in some cases adding custom attributes like data-* helps to easily access extra data related to the Option selected without making additional ajax call.

LaravelCollective HTML is an awesome package to created HTML forms in Laravel. It provides a lot of features to help to build simple and complex forms.

If you wanted to add some custom attributes in Select-Option tag, that is something like this:

<select>
	<option value="1" data-rate=10>Tax-1</option>
	<option value="2" data-rate=18>Tax-2</option>
	<option value="5" data-rate=20>Tax-3</option>
</select>

This is easy if you do it using a Loop, but using loops for every select field where you want to add it can be a pain.

Luckily LaravelCollective-HTML has an option for it in "Form::select". So you don’t have to use Loops.
If you look into the Select method signature, it looks like this:

/**
     * Create a select box field.
     *
     * @param  string $name
     * @param  array  $list
     * @param  string $selected
     * @param  array  $selectAttributes
     * @param  array  $optionsAttributes
     *
     * @return \Illuminate\Support\HtmlString
     */
    public function select(
        $name,
        $list = [],
        $selected = null,
        array $selectAttributes = [],
        array $optionsAttributes = []
    ) {

	}

The last parameter is where you can pass extra attributes to be added in option tag.

So for the above example, the optionsAttributes parameter will be:

$optionsAttributes = [1 => ['data-rate' => 10], 2 => ['data-rate' => 18], 5 => ['data-rate' => 18] ];

For example: If you want to show a list of tax rates:

//Get all tax the business.
$all_taxes = TaxRate::where('business_id', $business_id);

//Create an array of option attribute
$tax_attributes = collect($all_taxes->get())
			->mapWithKeys(function ($item) {
                        	return [$item->id => ['data-rate' => $item->amount, 'data-type' => $item->type ]];
                        })->all();

In view:

Form::select("tax", $all_taxes, null, [], $tax_attributes);

I hope this small tip is helpful.
Although this option is present but is not described in the documentation so thought of sharing.