Laravel: How to serve requests with HTML and JSON (with DRY)

Luís Nóbrega
4 min readJan 2, 2021
Photo by Kyle Sung on Unsplash

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?

Photo by Keagan Henman on Unsplash

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.

--

--

Luís Nóbrega
Luís Nóbrega

Written by Luís Nóbrega

Web Developer at 25friday. Likes to travel, write and being a father.