1

In Laravel 5.2, is there a particular way (handler) to check whether a route is existing or not? Let's say, for a basic URL like:

http://www.example.com/laravel

I then want to handle the non-existing URLs (like: /laravel) from my Main Page Router, which is:

Route::get('/{page}', funtion(){
    //check if $page is a valid route URL? Or 404?
});

How do I purposely check whether this route is a valid one or not?

honk
  • 9,137
  • 11
  • 75
  • 83
夏期劇場
  • 17,821
  • 44
  • 135
  • 217

3 Answers3

4

I use the following as my last route:

Route::any('{catchall}', function($page) {
    abort(404);
} )->where('catchall', '(.*)');

If you are not aware yet, abort(404) will return the view 404.blade.php from resources/views/errors.

user2094178
  • 9,204
  • 10
  • 41
  • 70
3

Simply put your Route::get('/{page}','MainController@getPage'); last. That way if it finds another route before it will use it but if it doesn't then it will get caught by this. For example:

Route::get('/welcome','WelcomeController@getWelcome');
Route::get('/test','TestController@getTest');
Route::get('/{page}','MainController@getPage');

If you were to hit /welcome or /test it should route them to the correct controller. If you where to hit /hello it should go to the MainController and hit function getPage($page) with $page being the page you hit.

If it hits MainController@getPage you know it was basically a 404.

If you need to know before you hit the route for some reason you could create something like this:

Route::get('/checkurl/{page}',function($page) {
    $exists = Route::has('/' . $page);
    return (new Response(json_encode(['exists'=>$exists]),200);
});
Pitchinnate
  • 7,517
  • 1
  • 20
  • 37
0

Adding last route with any catch doesn't works anymore with laravel 5.5.1+

TGA
  • 73
  • 1
  • 7