Rareș Urs
Rareș Urs

Reputation: 71

Php Laravel 404 routing

I have a problem with Laravel. I am working on an api, and every rout gives me 200. I want to create a 404 error page if the route does not exist in the routes/api.php

These are my routes:

Route::group(['prefix' => 'v1'], function($request) {
    //Account management
    Route::group(['prefix' => 'auth'], function ($request) {
        Route::post('/login', 'API\V1\AuthController@login');
        Route::post('/register', 'API\V1\AuthController@register');
        Route::get ('/logout', 'API\V1\AuthController@logout');
        Route::post('/reset', 'API\V1\AuthController@reset');
    });

    //AUTHENTICATED ROUTES
    Route::group(['middleware' => 'jwt'], function ($request) {

        //Api info
        Route::group(['prefix' => 'auth'], function ($request) {
            Route::get ('/appdata', 'API\V1\AuthController@appdata');
        });

        //Workouts
        Route::group(['prefix' => 'calls'], function ($request) {
            Route::get('/', 'API\V1\WorkoutController@viewAll');
            Route::get('/{workout_id}', 'API\V1\WorkoutController@get');
        });

        //Products
        Route::group(['prefix' => 'products'], function ($request) {
            Route::get('/', 'API\V1\ProductController@viewAll');
            Route::get('/{product_id}', 'API\V1\ProductController@get');
            //Route::post('/add', 'API\V1\ProductController@add');
        });

        //Users
        Route::group(['prefix' => 'users'], function ($request) {
            Route::get('/', 'API\V1\UserController@getUsers');
            Route::get('/{id}/', 'API\V1\UserController@getById');
        });

    });

});

For example if I go to: localhost:/abc -> I want to load a 404 error page.

Thank you!

Upvotes: 0

Views: 791

Answers (2)

Jaykumar Patil
Jaykumar Patil

Reputation: 359

Go to handler.php and include following in handle() method

if($e instanceof NotFoundException) {
    return view('notFoundView');
}

Upvotes: 1

Rareș Urs
Rareș Urs

Reputation: 71

I have managed to fix it. in web.php and api.php I had to add the following line.

Route::get('/{any}', function ($any) {

    return view('errors');

})->where('any', '.*');

Now everytime a route is not matched, I get a custom error page(404 and 500).

Upvotes: 0

Related Questions