8

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
}
Community
  • 1
  • 1
DevDavid
  • 195
  • 1
  • 1
  • 18
  • can you echo `$request`? – Agam Banga May 04 '17 at 11:05
  • Yes, it delivers me the Request headers: `GET /exists HTTP/1.1 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Accept-Language: en-us,en;q=0.5 Host: localhost User-Agent: Symfony/3.X` – DevDavid May 04 '17 at 11:08
  • this seems to be correct, are you sure the route already exists? could you dump the `$routes` ? – yazfield May 04 '17 at 12:54

3 Answers3

8

simply use if Route::has('example')

DrCod3r
  • 91
  • 2
  • 6
5

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.

Mozammil
  • 8,520
  • 15
  • 29
  • I get the exception `Call to undefined method Illuminate\Routing\Route::getPath()` if I use it with `Illuminate\Support\Facades\Route;`? – DevDavid May 04 '17 at 17:56
  • Updated for Laravel 5.4 compatibility. – Mozammil May 04 '17 at 19:31
  • Thanks for the update. It shows me the slugs now, but I have routes which are more complicated like `/foo/{id}-{name}` or `/{foo}/{bar}-{foobar}` or `/{foo}?param={bar}&param2={bar2}` etc. Any ideas? – DevDavid May 04 '17 at 20:17
  • Well the code above will get you the routes that are defined in your Routes file. I am exploding it and doing some manipulation to get the slug but you can just check for an instance of $route->uri instead. It should be easy enough to modify the code above a bit to get what you want. – Mozammil May 04 '17 at 20:20
5

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')
Orici
  • 411
  • 6
  • 12