64 lines
2.5 KiB
PHP
64 lines
2.5 KiB
PHP
@props([
|
|
'id' => '', // unique ID
|
|
'class' => '', // extra CSS classes
|
|
'name' => '', // select name
|
|
'options' => [], // array of options, optgroups, or rich option defs
|
|
'selected' => null, // selected value (falls back to old())
|
|
'placeholder' => '', // optional placeholder option (disabled)
|
|
'style' => '', // raw style string
|
|
'required' => false, // true/false or truthy value
|
|
'autocomplete' => '',
|
|
])
|
|
|
|
@php
|
|
// prefer old() value if present, otherwise selected prop
|
|
$current = old($name, $selected);
|
|
|
|
$isSelected = function ($value) use ($current) {
|
|
// cast to string so '1' and 1 match
|
|
return (string) $value === (string) $current;
|
|
};
|
|
|
|
$renderOption = function ($value, $label, $attrs = []) use ($isSelected) {
|
|
$attrString = collect($attrs)->map(function ($v, $k) {
|
|
if (is_bool($v)) return $v ? $k : '';
|
|
return $k.'="'.e($v).'"';
|
|
})->filter()->implode(' ');
|
|
|
|
$selectedAttr = $isSelected($value) ? ' selected' : '';
|
|
|
|
return '<option value="'.e($value).'"'.$selectedAttr.($attrString ? ' '.$attrString : '').'>'.e($label).'</option>';
|
|
};
|
|
@endphp
|
|
|
|
<select id="{{ $id }}" name="{{ $name }}" autocomplete="{{ $autocomplete }}"
|
|
{{ $attributes->merge(['class' => 'select '.$class]) }}
|
|
@if($style !== '') style="{{ $style }}" @endif
|
|
@required($required)>
|
|
|
|
@if($placeholder !== '')
|
|
<option value="" disabled @selected((string) $current === '')>
|
|
{{ $placeholder }}
|
|
</option>
|
|
@endif
|
|
|
|
@foreach($options as $key => $opt)
|
|
{{-- optgroup: 'Group label' => [ ...options... ] --}}
|
|
@if(is_array($opt) && !array_key_exists('value', $opt) && !array_key_exists('label', $opt))
|
|
<optgroup label="{{ $key }}">
|
|
@foreach($opt as $value => $label)
|
|
{!! $renderOption($value, $label) !!}
|
|
@endforeach
|
|
</optgroup>
|
|
|
|
{{-- rich option: [ 'value' => 'en', 'label' => 'English', 'attrs' => ['data-x' => 'y', 'disabled' => true] ] --}}
|
|
@elseif(is_array($opt) && array_key_exists('value', $opt))
|
|
{!! $renderOption($opt['value'], $opt['label'] ?? $opt['value'], $opt['attrs'] ?? []) !!}
|
|
|
|
{{-- simple options: [ 'en' => 'English', ... ] --}}
|
|
@else
|
|
{!! $renderOption($key, $opt) !!}
|
|
@endif
|
|
@endforeach
|
|
</select>
|