I want to get only API route names. How can I get all my route names inside of my api.php ?
I'm trying the code below but it lists all the routes of my app.
Route::getRoutes();
I'm waiting for your help
CodePudding user response:
I had similar issue and clean Laravel 9.
There are few ways to do that, you may get all contents of the api.php, or directly get all information from your RouteServiceProvider.php.
I changed my RouteServiceProvider.php
class RouteServiceProvider extends ServiceProvider
{
/**
* The path to the "home" route for your application.
*
* This is used by Laravel authentication to redirect users after login.
*
* @var string
*/
public const HOME = '/dashboard';
public const API_PREFIX = '/api'; // I added this line
and changed boot method to this:
/**
* Define your route model bindings, pattern filters, etc.
*
* @return void
*/
public function boot()
{
$this->configureRateLimiting();
$this->routes(function () {
Route::prefix(self::API_PREFIX) // to make it dynamic
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes/api.php'));
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
});
}
After that this code should give you all the api routes:
use Illuminate\Support\Facades\Route;
collect(Route::getRoutes())->filter(function ($route){
return $route->action['prefix'] === RouteServiceProvider::API_PREFIX;
});
Or you can use Str::startsWith
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Str;
collect(Route::getRoutes())->filter(function ($route){
return Str::startsWith($route->action['prefix'], RouteServiceProvider::API_PREFIX);
});
You can get all the information from the routes.
CodePudding user response:
One way to determine is by checking the prefix:
$apiRoutes = collect();
$apiRoutesNames = [];
foreach (\Route::getRoutes() as $route) {
if ($route->action['prefix'] !== 'api') {
continue;
}
$apiRoutes->push($route);
$apiRoutesNames[] = $route->action['as'];
}
$apiRoutesNames = array_filter($apiRoutesNames);
This will work if you did not change the prefix in app/Providers/RouteServiceProvider.php