Laravel: The Fantastic 4 Interfaces — Wrap up

Leaning the Response code, one implementation at a time.

Italo Baeza Cabrera
2 min readSep 2, 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.

How the framework checks the Response

The great tip bits are in the Router class. The toResponse() method is responsible of checking what the controller returns, and create a Response from it.

It will cycle for every type instance possible, but we can resume this in four points:

  1. If it’s a Responsable instance, let the class handle the Response content entirely and call it a day.
  2. If it’s a PSR-compatible Response, create the Response.
  3. Okay, then it may be something that may be casted to JSON, so it will create a JsonResponse. If it is an Eloquent Model, add the HTTP 201 code if it was created recently.
  4. Fine, it the response is anything, ANYTHING, that is not a Symfony Response will be casted as a normal Response.

How the Response checks the type

A brief look around the setContent() method of the Response gives its inner workings.

As we can see, first it will check if the content should be JSON, something that will be true if is an instance of Arrayable, Jsonable, ArrayObject, JsonSerializable, or just a simple array. In any of these case, the content will be transformed to JSON, and it will set the Content header as application/json.

The latter is done because you may make a normal Response but include a class that should be JSON-able, it will not transform the Response instance to a JsonResponse. Don’t worry, you are not missing too much.

If not, it will check if is an instance of Renderable, meaning that the whole content should be handled by the class instance, and will call the render() method and set the whole content for the Response.

Finally it will try to cast the content (whichever it may be) it as a string. If it can’t, then it will fail miserably.

The framework will push out the Response and the browser will see it. And that’s it. Good night.

--

--

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

No responses yet