Laravel Web Route or API Routes for application with VueJS in front end

Viewed 3196

We're currently developing a multipage app using VueJS as frontend javascript framework, Element.io as CSS framework.

We're not exposing any web services or some kind.

Our application is responsive - users can create records using desktop and mobile.

Do I need to create API routes or WEB routes is sufficient enough? Are there any scenario you can think of that I need an API route?

1 Answers

Web routes are for frontend views where API routes would be for API calls, you would definitely need to separate them as your VueJS will make calls to your API with JSON and get a JSON response in return with error codes to handle your errors efficiently.

Web Controller:

return view('blade_file')->with(compact('var1', 'var2'));

If you set the error codes here, it will show you the blade file for that error code, eg. 404 will show you the blade view file at ./resources/views/errors/404.blade.php but your application will expect JSON response instead of HTML response.

API Controller:

return response()->json(compact('var1', 'var2'), 200); // success

return response()->json(['error' => 'bad request'], 400); // bad request

If you set error codes here, you will still get a JSON response, just with the error code specified.

Conclusion:

Separate your frontend and backend with API and Web routes as requests/responses are handled differently.

Notes:

  • Remember to add your CSRF token in your header when making ajax/axios requests to this API.
  • Make sure your middleware is api. If the API only allow authenticated users, you would need the middleware to be auth:api and you would need to use Laravel Passport.
  • Remember to add the namespace of Api to your API routes, either in routes/api.php file or app/Providers/RouteServiceProvider.php.
Related