<?php
 namespace App\Rules; use App\Models\Menu; use App\Models\MenuItem; use Closure; use Illuminate\Contracts\Validation\ValidationRule; class ParentMenuItemRule implements ValidationRule { public function __construct( private Menu $menu, private ?MenuItem $item = null, ) {} public function validate(string $attribute, mixed $value, Closure $fail): void { if ($value === null) return; $parent = MenuItem::find($value); if (! $parent || $parent->menu_id !== $this->menu->id) { $fail('Invalid parent: must be in the same menu.'); return; } if ($parent->parent_id !== null) { $fail('Maximum nesting depth is 2 levels.'); return; } if ($this->item && $this->item->id === (int) $value) { $fail('Item cannot be its own parent.'); } } } 