Laravel 11.x 实现无限级分类需校验同 parent_id 下 name 唯一:使用 Rule::unique()->where() 动态限定父级,模型中补充 isNameUniqueUnderParent() 方法,并在数据库建立 parent_id 与 name 的联合唯一索引(parent_id 设为 0 表示根节点)。

在 Laravel 11.x 中实现无限级分类(如树形结构的分类表),同时校验「同级分类名称唯一」,不能简单用 unique:categories,name,否则会跨层级冲突(比如不同父级下允许重名,但同父级下必须唯一)。关键在于:校验需限定在同一父节点(parent_id)下名称不重复。
校验逻辑:同 parent_id 下 name 唯一
假设分类模型为 Category,数据表含字段:id、name、parent_id(可为 null 表示一级分类)。校验规则应动态排除当前记录(编辑时)、并按 parent_id 分组判断:
- 新增时:检查
parent_id = ?且name = ?的记录不存在 - 编辑时:检查
parent_id = ?且name = ?的记录存在且id != 当前id
使用 Rule::unique() 动态指定 where 条件
在 Request 或控制器验证中,用 Rule::unique() 配合 where() 实现精准约束:
use Illuminate\Validation\Rule;
// 新增/编辑请求验证规则示例
$rules = [
'name' => [
'required',
'string',
'max:100',
Rule::unique('categories', 'name')
->where(fn ($query) => $query->where('parent_id', request('parent_id') ?? null))
->ignore($category->id ?? null),
],
'parent_id' => 'nullable|exists:categories,id',
];
注意:request('parent_id') 在表单提交时必须存在;若前端未传(如一级分类设为 null),Laravel 会自动匹配 parent_id IS NULL,符合预期。
模型层面补充:避免逻辑遗漏
仅靠表单验证不够,建议在模型的 save() 或观察者中再次校验,防止绕过 API 直接调用模型操作:
- 在
Category::saving()中 throw ValidationException 或 return false - 或封装一个
isNameUniqueUnderParent($name, $parentId, $exceptId = null)方法复用
例如:
public function isNameUniqueUnderParent(string $name, ?int $parentId, ?int $exceptId = null): bool
{
$query = static::where('name', $name)->where('parent_id', $parentId);
if ($exceptId) {
$query->where('id', '!=', $exceptId);
}
return ! $query->exists();
}
数据库加联合唯一索引(强烈推荐)
光靠 PHP 层验证有并发风险。应在数据库增加联合唯一索引,从根本上保证一致性:
Schema::table('categories', function (Blueprint $table) {
$table->unique(['parent_id', 'name']);
});
注意:parent_id 允许为 NULL,MySQL 中多个 NULL 不参与唯一索引判定,因此多个一级分类(parent_id IS NULL)可以重名 —— 这不符合需求。解决办法是:
- 将
parent_id默认设为0(非 NULL),一级分类统一用parent_id = 0 - 或使用函数索引(MySQL 8.0.13+):
$table->unique(['parent_id', 'name'])->where('parent_id IS NOT NULL');,再单独对parent_id IS NULL做业务限制
更稳妥做法:统一用 parent_id = 0 表示根节点,并在迁移中设置默认值和索引:
$table->unsignedBigInteger('parent_id')->default(0);
$table->unique(['parent_id', 'name']);
对应模型中可定义访问器简化使用:
protected $casts = ['parent_id' => 'integer'];
public function getParentIdAttribute($value)
{
return $value === 0 ? null : $value;
}
public function setParentIdAttribute($value)
{
$this->attributes['parent_id'] = $value ?? 0;
}
这样既保持语义清晰(null 表示无父级),又让数据库索引生效,验证与存储完全对齐。











