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

kamrankb's avatar

How to get route name from url (not current url)?

Working on dynamic routing for all frontend urls but while accessing admin routes it goes to abort condition which is on the mentioned route's function.

Route::get('/{slug?}', 'slug' )->where('slug','(.*)')->name('slug');

FrontController.php

 public function slug(Request $request, $slug=null) {
    if ($slug == "admin") {
        return redirect()->route('login');
    }
    
    
        if (Str::contains($slug, 'admin/')) {
        $routes = Route::getRoutes();
        $request = Request::create($slug);
        try {
            $route->match($request,'admin.dashboard');
            //How to access requested url's route name to redirect there

        } catch (\Symfony\Component\HttpKernel\Exception\NotFoundHttpException $e) {
            abort(404);
        }
    }

    if ($slug == "login") {
        return view('auth.login');
    }

    if ($slug == null) {
        $page = Pages::where('url', '')->first();
    }

    if (empty($page)) {
        abort(404);
    }

    $contentWithBlade = Blade::render($page->pages_content);
    $session = $request->session()->put('key', $page);

    return view('frontend.pages.template', compact('contentWithBlade', 'page'));
}

Any suggestions how to get route name against route url?

0 likes
6 replies
Snapey's avatar

why? Laravel already dynamically routes?

if /admin always goes to login then just create a dedicated route

same for /login

I assume this route comes AFTER all your other routes?

1 like
kamrankb's avatar

@Snapey I'm getting the pages to render from database that's why created slug function to have dynamic routing for seo purpose to edit from admin panel.

Thank you @snapey I've placed this route after all routes by calling custom admin.php routes file first. It's working now, let me test again!

Snapey's avatar
Snapey
Best Answer
Level 122

@kamrankb this seems waay to complicated. You just want to find a post by its slug?

Route::get(/{slug}, [FrontendController::class,'show']);

FrontendController

public function show(Request $request, $slug)
{
	$page = Pages::where('url', $slug)->firstOrFail();
    return view('frontend.pages.template', compact('page'));
}

Something like that should be sufficient.

kamrankb's avatar

@Snapey Yes after putting route at the end, your recommendation would work perfectly!

kamrankb's avatar

Thank you @Snapey for your timely response and great contribution to the community :)

Please or to participate in this conversation.