New Response types in Laravel using Custom Facades

laravel

Laravel provides some great tools for simplifying the development of web applications. One of them is the Response facade, which allows us to quickly and easily send information back to the requester (browser window in the case of a normal user, third-party application in the case of API access).

Some examples include:

But what if we want to send back some other kind of response, like streaming a comma separated values (CSV) file back to the user?

There are a couple of approaches. The first (and easiest) is using macros, which are described in the Laravel documentation. The second is a little more complicated, but (in my opinion) lends itself to a better application architecture.

Macros

We can define macros anywhere in the chain of execution, as long as it occurs before the usage of the macro (usage typically occurs in your controller classes). However, it’s recommended that you define them either in the routes.php file (for small projects), in your controllers or in a custom helper class (for larger projects).

Here’s an example of how we’d implement the CSV example using this approach:

Custom Response Facade

The other approach is to define a custom response facade. Using this approach, we leverage Laravel’s IoC container to intercept the resolution of the “Response” class and inject our own implementation that extends the core response class.

The benefit of this approach is that we can isolate all response related extensions into their own namespace. This is not necessary for small projects, but if we want to implement many different custom response types, this isolation makes it easy to constrain the complexity of our application.

To start off, we implement the custom Response facade:

And then update the app.php file to reflect this:

… and that’s it!

We can now use the custom response facade in our controllers as such:


Want to find out more?

We've worked with businesses just like yours to execute successful web projects helping them to optimise operations, improve marketing, and sell more online with custom software solutions. Reach out and tell us about your project for a free no-commitment consultation.

Find out more