I'm not sure if these are the best ways, but I can think of 2 ways right now. The first would be to use route names. I put all my admin routes inside a route group so their route names all are prefixed with 'admin.' so if you do something similar, you can then do something like this:
public function handle($request, Closure $next)
{
$routeName = Route::currentRouteName();
// isAdminName would be a quick check. For example,
// you can check if the string starts with 'admin.'
if ($this->isAdminName($routeName))
{
// If so, he's already accessing an admin path,
// Just send him on his merry way.
return $next($request);
}
// Otherwise, get the admin route name based on the current route name.
$adminRouteName = 'admin.' . $routeName;
// If that route exists, redirect him there.
if (Route::has($adminRouteName))
{
return redirect()->route($adminRouteName);
}
// Otherwise, redirect him to the admin home page.
return redirect('/admin');
}
The second method would be to work directly with the route uri.
public function handle($request, Closure $next)
{
$uri = $request->path();
// isAdminUri would be a quick check to see
// if the route starts with 'admin'
if ($this->isAdminUri($uri))
{
// If he's already accessing an admin path,
// Just send him on his merry way.
return $next($request);
}
// Create a new request for the admin path
$adminUri = 'admin/' . $uri;
$adminRequest = $request->create($adminUri);
// Get route collection
$routes = Route::getRoutes();
try {
// If we find a match, take the user there.
$routes->match($adminRequest);
return redirect($adminUri);
}
catch (\Symfony\Component\HttpKernel\Exception\NotFoundHttpException $e) {
// Otherwise, we didn't find a match so take the user to the admin page.
return redirect('/admin');
}
}