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.
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: