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

Laravel嵌套循环HTML Option层级缩进递增问题求解

解决嵌套分类Option层级缩进问题

核心是在递归过程中传递层级深度参数,根据深度生成对应数量的缩进,替代固定一级缩进的写法。

1. 修改递归视图,增加深度控制

编辑nested_category_html_select.blade.php,新增$depth参数(默认0,对应根分类层级),根据深度生成缩进:

@foreach($categories as $category)
    <option value="{{ $category->id }}" {{ isset($selectedId) && $selectedId == $category->id ? 'selected' : '' }}>
        {{ str_repeat('&nbsp;&nbsp;', $depth) }}{{ $category->name }}
    </option>
    {{-- 递归调用子分类时,深度+1 --}}
    @if($category->children->isNotEmpty())
        @include('nested_category_html_select', [
            'categories' => $category->children,
            'depth' => $depth + 1,
            'selectedId' => $selectedId ?? null
        ])
    @endif
@endforeach

2. 初始调用视图时传入默认深度

在form.blade.php里引入递归视图时,指定初始深度为0:

<select name="category_id">
    @include('nested_category_html_select', [
        'categories' => $rootCategories,
        'depth' => 0,
        'selectedId' => old('category_id', $model->category_id ?? null)
    ])
</select>

3. 确保Controller传递正确的分类数据

Controller中要预加载子分类,避免N+1查询:

// 示例Controller代码
public function create()
{
    // 假设Category模型有children自关联(hasMany)
    $rootCategories = Category::whereNull('parent_id')->with('children')->get();
    return view('form', compact('rootCategories'));
}

可选:自定义缩进符号

如果不想用空格,可替换成—或其他符号,修改str_repeat的内容即可:

{{ str_repeat('— ', $depth) }}{{ $category->name }}

这样根分类无缩进,子分类、孙分类会随层级加深自动增加缩进量,符合预期效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 01:20:05