Dev*_*vid 10 php routes laravel laravel-5.4
通过提供 URL,我想知道是否有任何方法可以确定该 URL 是否存在于我的 Laravel 应用程序中(与想要检查外部 URL 的“如何通过 Laravel 检查 URL 是否存在? ”相比)?
我尝试了这个,但它总是告诉我网址不匹配:
$routes = \Route::getRoutes();
$request = \Request::create('/exists');
try {
$routes->match($request);
// route exists
} catch (\Symfony\Component\HttpKernel\Exception\NotFoundHttpException $e){
// route doesn't exist
}
Run Code Online (Sandbox Code Playgroud)
在我的一个 Laravel 应用程序中,我通过执行以下操作来实现这一目标
private function getRouteSlugs()
{
$slugs = [];
$routes = Route::getRoutes();
foreach ($routes as $route)
{
$parts = explode('/', $route->uri());
foreach ($parts as $part)
{
$slug = trim($part, '{}?');
$slugs[] = $slug;
}
}
return array_unique($slugs);
}
Run Code Online (Sandbox Code Playgroud)
此函数将有助于获取 Laravel 中注册的所有 slugs,然后通过一个简单的操作,in_array您可以检查该 slug 是否已被保留。
编辑
根据您的评论,您可以扩展以下功能
private function getRouteSlugs()
{
$slugs = [];
$routes = Route::getRoutes();
foreach ($routes as $route)
{
$slugs[] = $route->uri();
}
return array_unique($slugs);
}
Run Code Online (Sandbox Code Playgroud)
这将为您提供一系列项目,如下所示:
0 => "dashboard/news"
1 => "dashboard/post/news"
2 => "dashboard/post/news/{id}"
3 => "dashboard/post/news"
Run Code Online (Sandbox Code Playgroud)
从这里应该很容易进行比较。
Route::has('route_name')检查路线是否存在(在路线文件上)。
示例:测试一些应用程序路由
<?php
namespace Tests\Feature;
use App\Models\Users\User;
use Illuminate\Support\Facades\Route;
use Tests\TestCase;
class RouteTest extends TestCase
{
private $routes = [
'home',
'users.index',
'employees.index',
'logs.index',
];
public function setUp(): void
{
parent::setUp();
// Put an admin on session
$adminUser = User::getFirstAdmin();
$this->actingAs($adminUser);
}
public function testRoutes()
{
foreach ($this->routes as $route) {
$this->assertTrue(Route::has($route));
$response = $this->get(route($route));
$response->assertStatus(200);
}
}
}
Run Code Online (Sandbox Code Playgroud)
版
快速的方法是在终端上使用修补程序输入进行检查:
php artisan tinker
Run Code Online (Sandbox Code Playgroud)
然后:
Route::has('your_route')
Run Code Online (Sandbox Code Playgroud)
或者
route('your_route')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18777 次 |
| 最近记录: |