Howard
Howard

Reputation: 3758

How can I check if a URL exists via Laravel?

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?

Upvotes: 6

Views: 17140

Answers (4)

Max S.
Max S.

Reputation: 1461

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 ...
}

Upvotes: 4

Bhargav Kaklotara
Bhargav Kaklotara

Reputation: 1458

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;        
   }

Upvotes: 2

aphoe
aphoe

Reputation: 2716

try this function

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

    return false;
}

Upvotes: 0

lukasgeiter
lukasgeiter

Reputation: 152870

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
}

Upvotes: 9

Related Questions