Great question! Laravel does not provide a built-in way to resolve a full URL (like a referer) back to a named route directly. However, you can achieve this by using the router to match the referer URL and then check its route name.
Here’s how you can do it:
- Parse the referer URL to get the path.
- Use the router to match the path to a route.
- Check the route's name.
Here’s a practical example:
use Illuminate\Support\Facades\Route;
use Illuminate\Http\Request;
$referer = request()->header('referer');
if ($referer) {
// Parse the path from the referer URL
$refererPath = parse_url($referer, PHP_URL_PATH);
// Create a new Request instance for the referer path
$fakeRequest = Request::create($refererPath);
// Match the request to a route
$route = app('router')->getRoutes()->match($fakeRequest);
// Now you can check the route name
if ($route->getName() === 'datasets.all') {
// Do something
} elseif ($route->getName() === 'reports.view') {
// Do something else
} else {
// Fallback
}
}
Notes:
- This approach works even if your routes have parameters (like slugs or IDs).
- If the referer is from an external site or doesn't match any route,
$route->getName()will benull. - Always validate and sanitize the referer, as it can be spoofed.
Summary:
You can match a referer URL to a named route by parsing the path, creating a fake request, and using Laravel's router to resolve the route and check its name. This avoids hardcoding URLs and works with dynamic parameters.