6

I did look at this answer:

How can I check if a URL exists via PHP?

However, I was wondering if a method exists in Laravel that can check if a URL exists (not 404) or not?

Community
  • 1
  • 1
Howard
  • 3,648
  • 13
  • 58
  • 86

4 Answers4

9

I assume you want to check if a there's a route matching a certain URL.

$routes = Route::getRoutes();
$request = Request::create('the/url/you/want/to/check');
try {
    $routes->match($request);
    // route exists
}
catch (\Symfony\Component\HttpKernel\Exception\NotFoundHttpException $e){
    // route doesn't exist
}
lukasgeiter
  • 147,337
  • 26
  • 332
  • 270
  • 1
    Is there a way to check an external URL via Laravel? – Howard Jan 09 '15 at 23:07
  • The OP mentioned he wants to check an external URL. He didn't say a route within the app. – Max S. Dec 09 '19 at 12:36
  • 1
    for some reason I am not getting the ```NotFoundHttpException``` even when the route does not exists. I instead get a route object with uri: `{fallbackPlaceholder}`. Any ideas? – Themba Clarence Malungani Mar 16 '21 at 13:23
  • @ThembaClarenceMalungani Like this: ``` protected function routeExists(string $url): bool { $routes = Route::getRoutes(); $request = Request::create($url); return (bool) $routes->match($request)->getName(); } $this->routeExists($this->request->fullUrl()) ``` – Kal Nov 05 '21 at 12:15
3

Since you mentioned you want to check an external URL (eg. https://google.com), not a route within the app , you can use use the Http facade in Laravel as such (https://laravel.com/docs/master/http-client):

use Illuminate\Support\Facades\Http;

$response = Http::get('https://google.com');

if( $response->successful() ) {
    // Do something ...
}
Max S.
  • 1,383
  • 14
  • 25
2

Not particular laravel function, but you can make a try on this

 function urlExists($url = NULL)
    {
        if ($url == NULL) return false;
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $data = curl_exec($ch);
        $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        return ($httpcode >= 200 && $httpcode < 300) ? true : false;        
   }
Bhargav Kaklotara
  • 1,310
  • 12
  • 22
0

try this function

function checkRoute($route) {
    $routes = \Route::getRoutes()->getRoutes();
    foreach($routes as $r){
        if($r->getUri() == $route){
            return true;
        }
    }

    return false;
}
aphoe
  • 2,586
  • 1
  • 27
  • 31