You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在spatie/laravel-html中为select选项添加自定义属性?

解决spatie/laravel-html为select选项添加自定义属性的问题

原Laravel Collective实现方式

控制器代码:

$contact_detail_types = ContactDetailType::pluck('contact_detail_type','id')->all();
$option_attributes = collect(ContactDetailType::all())
    ->mapWithKeys(function ($item) {
        return [$item->id => ['data-input-mask' => $item->input_mask]];
    })->all();

Blade模板(Laravel Collective):

{!! Form::select('contact_detail_type_id', $contact_detail_types, null, $option_attributes) !!}

spatie/laravel-html的正确实现

spatie/laravel-html没有直接传入全局选项属性的参数,但可以通过闭包引用外部变量的方式,将$option_attributes传递到children方法的回调中,为每个option设置自定义属性:

Blade模板代码修改如下:

{{ 
html()->select('contact_detail_type_id')
   ->children($contact_detail_types, function ($contact_detail_type, $id) use ($option_attributes) {
       // 使用attributes()批量设置属性,?? [] 避免无对应属性时出错
       return html()->option($contact_detail_type, $id)->attributes($option_attributes[$id] ?? []);
   })
   ->class('form-control kt-select2' . ($errors->has('contact_detail_type_id') ? ' is-invalid' : '')) 
}}

关键说明

  • 利用PHP闭包的use()语法,让回调函数能访问外部的$option_attributes变量;
  • 使用attributes()方法(而非单个属性的attribute())批量设置option的自定义属性,匹配你在控制器中生成的数组格式;
  • 添加?? []做容错处理,确保当某个选项ID没有对应属性时不会抛出错误。

内容的提问来源于stack exchange,提问作者SupaMonkey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 11:17:14