You can use the getRoutes() method of the Illuminate\Routing\Router class to get all the registered routes and then filter them by prefix using the Str::startsWith() method. Here's an example:
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Str;
$prefix = 'docs';
$routes = collect(Route::getRoutes())->filter(function ($route) use ($prefix) {
return Str::startsWith($route->uri, $prefix);
});
$menu = $routes->map(function ($route) use ($prefix) {
$uri = Str::after($route->uri, $prefix.'/');
$segments = explode('/', $uri);
$name = Str::title(str_replace('-', ' ', end($segments)));
$url = route($route->getName(), ['version' => $segments[0]]);
return compact('name', 'url');
})->values()->toArray();
return response()->json($menu);
In this example, we first define the prefix we want to filter by ($prefix = 'docs'). Then, we use the getRoutes() method to get all the registered routes and wrap them in a collect() function to make them easier to work with.
Next, we filter the routes using a closure that checks if the route's URI starts with the prefix using the Str::startsWith() method. We return true if it does, which keeps the route in the collection, and false otherwise, which removes it.
After filtering the routes, we use the map() method to transform each route into a menu item. We first extract the URI segments after the prefix using the Str::after() method. We then extract the last segment of the URI, which represents the menu item name, and format it using the Str::title() and str_replace() methods. Finally, we generate the URL for the route using the route() function and the route's name and version parameter.
We then use the values() method to reset the keys of the collection and the toArray() method to convert it to a plain PHP array. Finally, we return the menu as a JSON response using the response()->json() function.