通过提供一个URL,我想知道是否有办法确定我的Laravel应用程序中是否存在该URL(与想要检查外部URL的“How can I check if a URL exists via 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
}
答案 0 :(得分:1)
如果Route :: has('example')
仅使用答案 1 :(得分:0)
在我的一个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);
}
这个函数有助于获得在Laravel中注册的所有slug,然后使用简单的in_array
来检查该slug是否已被保留。
修改强>
根据您的评论,您可以扩展以下功能
private function getRouteSlugs()
{
$slugs = [];
$routes = Route::getRoutes();
foreach ($routes as $route)
{
$slugs[] = $route->uri();
}
return array_unique($slugs);
}
这将为您提供一系列项目:
0 => "dashboard/news"
1 => "dashboard/post/news"
2 => "dashboard/post/news/{id}"
3 => "dashboard/post/news"
从这里开始比较应该很容易。
答案 2 :(得分:0)
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);
}
}
}