Reputation: 325
By providing a URL I would like to know if there's any way to determine if the URL exists in my Laravel application (in comparison to "How can I check if a URL exists via Laravel?" which wants to check an external URL)?
I tried this but it always tells me the URL doesn't match:
$routes = \Route::getRoutes();
$request = \Request::create('/exists');
try {
$routes->match($request);
// route exists
} catch (\Symfony\Component\HttpKernel\Exception\NotFoundHttpException $e){
// route doesn't exist
}
Upvotes: 11
Views: 21807
Reputation: 119
simply use if Route::has('example')
. This checks for named route exisitence in case name match return true otherwise false
Upvotes: 10
Reputation: 431
Route::has('route_name')
check if the route exists (on routes files).
Example: test some app routes
<?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);
}
}
}
Edition
The fast way, check with tinker typing on the terminal:
php artisan tinker
then:
Route::has('your_route')
or
route('your_route')
Upvotes: 5
Reputation: 8750
In one of my Laravel application, I achieved it by doing the following
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);
}
This function would help to get all the slugs that are registered within Laravel and then with a simple in_array
you can check if that slug has been reserved.
EDIT
Based on your comment, you can extend the following function
private function getRouteSlugs()
{
$slugs = [];
$routes = Route::getRoutes();
foreach ($routes as $route)
{
$slugs[] = $route->uri();
}
return array_unique($slugs);
}
That will get you an array of items as such:
0 => "dashboard/news"
1 => "dashboard/post/news"
2 => "dashboard/post/news/{id}"
3 => "dashboard/post/news"
It should be easy enough from here to compare.
Upvotes: 5