Skip to content

Instantly share code, notes, and snippets.

@marekmurawski
Last active January 8, 2018 12:32
Show Gist options
  • Save marekmurawski/8855132 to your computer and use it in GitHub Desktop.
Save marekmurawski/8855132 to your computer and use it in GitHub Desktop.
Laravel macro Form::select() with optgroup based on Collection field
<?php
// You can put this code into /app/routes.php for testing
/*
* Form::selectOpt()
*
* Parameters:
* $collection A I\S\Collection instance
* $name The HTML "name"
* $groupBy Field by which options are grouped
* $labelBy Field to use as an option label (default="name")
* $valueBy Field to use as option's value (default="id")
* $value Value of selected item or items
* $attributes An array of additional HTML attributes
*/
Form::macro('selectOpt', function(ArrayAccess $collection, $name, $groupBy, $labelBy = 'name', $valueBy = 'id', $value = null, $attributes = array()) {
$select_optgroup_arr = [];
foreach ($collection as $item)
{
$select_optgroup_arr[$item->$groupBy][$item->$valueBy] = $item->$labelBy;
}
return Form::select($name, $select_optgroup_arr, $value, $attributes);
});
/*
* Form::selectOptMulti()
*
* A shortcut for Form::selectOpt with multiple selection
*/
Form::macro('selectOptMulti', function(ArrayAccess $collection, $name, $groupBy, $labelBy = 'name', $valueBy = 'id', $value = null, $attributes = array()) {
$attributes = array_merge($attributes, ['multiple' => true]);
return Form::selectOpt($collection, $name, $groupBy, $labelBy, $valueBy, $value, $attributes);
});
/*
* Test route
*
* Assumption:
*
* Product Model has "id", "name", and "category" fields
*
* Options will be grouped by "category" field
*/
Route::get('selectopt', function() {
return Form::selectOpt(Product::all(), 'product_id', 'category', 'name', 'id');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment