Laravel: The Fantastic 4 Interfaces — Wrap up

Leaning the Response code, one implementation at a time.

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 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 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 . 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 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 , , , , or just a simple . In any of these case, the content will be transformed to JSON, and it will set the header as .

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 . Don’t worry, you are not missing too much.

If not, it will check if is an instance of , meaning that the whole content should be handled by the class instance, and will call the 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.

Graphic Designer graduate. Full Stack Web Developer. Retired Tech & Gaming Editor.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store