Laravel: The Fantastic 4 Interfaces — Jsonable

Leaning the Response code, one implementation at a time.

Italo Baeza Cabrera
2 min readAug 12, 2019

Credit where is due. Last year I stumbled upon an article of Josip Crnković, in which he walked through some of the useful interfaces the framework has. In it, he discovers some that are used to send a Response to the browser.

After giving them a shot, I have to say these alleviates a lot of DRY problems and slims down multiple lines of code to just a few. In this series of articles I will check them out, as these may help you to code more easily your application.

Jsonable

When not creating the whole Response from the ground up, you may want to modify its content. Here, the Jsonable interface comes into play.

This interface is very simple: when you push out a class implementing the Jsonable interface, the Response contents will be automatically casted as a JSON string, and the Response will be an instance of JsonResponse.

There is a difference between this and the Responsable interface. The Responsable interfaces creates the whole response, while the Jsonable interface creates the contents, which in this case is JSON.

The class implementing the Jsonable interface must have thetoJson() method, which is responsible of returning a JSON string of the class, the rest is handled by the framework.

This is useful for API responses, or REST, since the Resources there need serialization prior to be sent. Indeed, the documentation has a whole page talking about it for the purpose of serializing Eloquent models.

If you have a class that always returns JSON, this is the best way to lean your controller code.

Note: when pushing out something to the browser, a Jsonable interface take precedence over the Renderable interface.

Example: Pushing a Podcast Status as JSON

In my Podcast Application, you can check the transcode status of a Podcast in a reactive manner through the web application. The frontend makes an AJAX Request to the application every 10 seconds (since it doesn’t use Broadcasting yet), and it receives JSON which is parsed into a progress bar.

We can just create a new PodcastStatus class that will receive the ID of the Podcast model, check its status, and return itself. The only thing I must take care now in my Controller is just to push this class instance out.

Wow, talking about one liners. And since the Router will check if the instance is Jsonable, it will automatically push a JsonResponse with our JSON data.

--

--

Italo Baeza Cabrera
Italo Baeza Cabrera

Written by Italo Baeza Cabrera

Graphic Designer graduate. Full Stack Web Developer. Retired Tech & Gaming Editor. https://italobc.com

Responses (1)