7
votes

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.

3
This type of url redirect every request to SpaController@index to make laravel+vue SPAAfraz Ahmad
You will have to use Vue-router's feature to show 404 pageAfraz Ahmad
But how can I make Route::fallback work? I need to show 404 for apiИлья Зеленько
it will work if it is at topAfraz Ahmad
Place fallback route above to spa routeAfraz Ahmad

3 Answers

13
votes

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.

2
votes

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','.*');
0
votes

I use get('/{any}' together with a where condition regular expression ('^(?!api\/)[\/\w\.-]*') : to catch "any" route apart from the api route:

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

so if I call any nonexistent API URL I get the laravel 404 error page.