To check if a given path exists in your application's route list, you can use the Route::getRoutes() method to retrieve all registered routes and then iterate over them to check if any route's URI matches the provided path. Here's how you can modify your validation logic to achieve this:
use Illuminate\Support\Facades\Route;
use Illuminate\Validation\Rule;
class UpdateProfileRequest extends FormRequest
{
/**
* Get the validation rules that apply to the request.
*/
public function rules(): array
{
return [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'lowercase', 'max:255', Rule::email()->strict()->preventSpoofing(), Rule::unique(User::class)->ignore($this->user()->id)],
'enhanced_at' => ['nullable', 'date'],
'bio' => ['required', 'string'],
'account' => [
'required', 'string', 'max:255', Rule::unique(User::class)->ignore($this->user()->id), function ($attribute, $value, $fail) {
$routes = Route::getRoutes();
foreach ($routes as $route) {
if ($route->uri() === $value) {
$fail('The username is invalid because it matches an existing route path.');
break;
}
}
}
],
];
}
}
Explanation:
- Route::getRoutes(): This method retrieves all the routes registered in your application.
- Iterate over routes: We loop through each route and use
$route->uri()to get the URI of the route. - Comparison: We compare the URI with the provided account name. If a match is found, we trigger a validation failure using
$fail().
This approach ensures that the account name does not conflict with any existing route paths in your application.