Implement a Custom Fluent Interface for Laravel to Vue Responses

Daniel Alvidrez
Apr 2, 2019 · 2 min read
Image for post
Image for post

I wanted to implement a custom fluent interface for responses designed to work with my vue application. Instead of using macros, I wanted to create a wrapper that implements specialized methods that operate on a JSON Response designed specially for my needs. The goal is to streamline communication from the backend to the frontend by formatting data in a way that is readily digestible by the client-side application and provides human readable methods that let me know the exact side effect of the response.

return apiResponse()
->commit('articles/update', $model)
->event('app:snackbar', "Article Updated!");

Response Helper

By adding a line to composer we can load a custom helper file with our new function that builds our custom response

"autoload": {
"files": [

Response Class

Instead of extending a Response class we instead create a wrapper that encapsulates our implementation and exposes a limited set of public methods.

I designed my class to work with Vue to commit data to my store or emit events programmatically. By implementing the Responsable contract Laravel knows that our new class can be converted into a response when it’s returned from a controller. The data_set helper allows us to set nested data properties easily which are then converted to a response. Our underlying dependency is the JsonResponse class.

Axios Integration

You can hook into an axios instance and setup interceptors to work with your new responsable api.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

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