Laravel: How to serve requests with HTML and JSON (with DRY)
One of the common problems of a web application is the need to return HTML and JSON to a request. Why? Imagine we have a SPA who needs the responses in JSON, and a backend that needs HTML. In this article, I will show you some ways on how to accomplish this in Laravel.
Why is this a problem?
This is a problem because we have the business logic, and two different ways of information to return, and is a good practice that our code fulfills the Don’t Repeat Yourself (DRY) principle.
DRY was coined by Andy Hunt and Dave Thomas in their book The Pragmatic Programmer, and it says that everything in our system should have only one representation. Nothing should be duplicated.
This principle will lead us to have the same code for the business logic, and different approaches to returning HTML and JSON on every request.
A simple solution to attend to this principle is to encapsulate our code, centralize functionality, and this way makes it easy to be used by different places of code.