#Dealing with overlapping routes

2 messages · Page 1 of 1 (latest)

hard island
#

Hello everyone. I have these routes in my app -


Route::get( '{operator:slug}/{cluster:slug}', [
    ViewsController::class,
    'show_cluster_single']);

Route::get('{template:slug}/{landingPage:slug}', [LandingPageController::class, 'display']);

Lets assume that I dont have the option to add an explicit prefix/suffix to one of these - How can i solve the issue where the first route fails - it won't simply return 404 but continue to checking the second one ({template:slug}/landingPage:slug}.

I thought about adding some kind of middleware to both like this -

Route::get( '{operator:slug}/{cluster:slug}', [
    ViewsController::class,
    'show_cluster_single',
] )->middleware('validate:operator,cluster');

Route::get('{template:slug}/{landingPage:slug}', [LandingPageController::class, 'display'])
    ->middleware('validate:template,landingPage');

and then in the middleware to check for the actual models -

class ValidateRouteParameters
{
    public function handle(Request $request, Closure $next, $type1, $type2)
    {
        if ($type1 == 'operator') {
            $operator = Operator::where('slug', $request->route('operator'))->first();
            if (!$operator) {
                return $next($request);
            }
        }
        if ($type1 == 'template') {
            $template = Template::where('slug', $request->route('template'))->first();
            if (!$template) {
                return $next($request);
            }
        }
        return $next($request);
    }
}

But it feels like this solution will have a serious impact on the performance of my app since it involves database queries for each request. Is there any other approach I am not aware of?

snow rover
#

I think the ONLY thing you'd be able to do in this situation is add a prefix to the slugs themselves so you can differentiate before making a query.

I.e. operators start with op-, clusters with cl- and templates with tl- or something.

That way you can use regex matching or simple prefixes in the route names to help with where it should be directed.

Other than that, can't see a good way!