Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: catch all routes where the path does not start with api

I use this starter Laravel + Vue SPA where I have such a router in web.php:

Route::get('/{any}', 'SpaController@index')->where('any', '.*');

But when I make a request for an api with a nonexistent url, I would like to return a response via

Route::fallback(function() {
    return response()->json(['message' => 'Not Found!'], 404);
});

This route does not work and instead of it the request goes to this route:

Route::get('/{any}', 'SpaController@index')->where('any', '.*');

I understand I need to change ->where('any', '.*'); but not sure how.

like image 368
Илья Зеленько Avatar asked Sep 18 '18 08:09

Илья Зеленько


2 Answers

Instead of this

Route::get('/{any}', 'SpaController@index')->where('any', '.*');

I use

Route::get('/{any}', 'SpaController@index')->where('any', '^(?!api).*$');

I was helped by this answer.

like image 83
Илья Зеленько Avatar answered Nov 07 '22 17:11

Илья Зеленько


If you want to show 404 page in laravel vue spa then use vue-router's 404 feature

vue routes should have a route like this

routes:[
    {path:'*',component:NotFound,name:'NotFound'},
...
]

NotFound component can be designed to show 404 page.

If you still want to make your fallback route work then place it above SPA route.

Route::fallback(function() {
return response()->json(['message' => 'Not Found!'], 404);
});

Route::get('/{any}','SpaController@index')->where('any','.*');
like image 2
Afraz Ahmad Avatar answered Nov 07 '22 17:11

Afraz Ahmad