我只想獲取 API 路由名稱。如何在 api.php 中獲取所有路由名稱?
我正在嘗試下面的代碼,但它列出了我的應用程式的所有路線。
Route::getRoutes();
我在等你的幫助
uj5u.com熱心網友回復:
我有類似的問題并清理了 Laravel 9。
有幾種方法可以做到這一點,您可以獲取 api.php 的所有內容,或者直接從您的 RouteServiceProvider.php 獲取所有資訊。
我改變了我的 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
并將引導方法更改為:
/**
* 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'));
});
}
之后,此代碼應為您提供所有 api 路由:
use Illuminate\Support\Facades\Route;
collect(Route::getRoutes())->filter(function ($route){
return $route->action['prefix'] === RouteServiceProvider::API_PREFIX;
});
或者你可以使用 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);
});
您可以從路線中獲取所有資訊。
uj5u.com熱心網友回復:
一種確定方法是檢查前綴:
$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);
如果您沒有更改前綴,這將起作用app/Providers/RouteServiceProvider.php
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/435919.html
