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.
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
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 the
toJson() 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.