Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

rawnato's avatar

Route path exists

Hello everyone, I am creating a route for user profiles in my application, and the route is the last one in the file, so it can look like this:

Route::get('/{user:account}', AccountController::class)->name('account');

So far, everything is fine and working correctly! I thought it would be nice to include validation when the user provides the account name, ensuring that the username provided does not matches the application's existing routes. I came up with the following validation in the FormRequest:

The problem is that the method Route::has($value) checks for the name of the route, not the path. Do you know how I can check if the path is in the route list?

0 likes
2 replies
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

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.

Please or to participate in this conversation.