Press "Enter" to skip to content

Json or View – whichever you want? – Laravel

Laravel has always been most customize-able web framework out there. It feels like we have full control over our application.

Macro is the one the best feature, developer adore in this framework. Check out this post for more.

In this one, I am posting a little bit of snippet which is useful for retrieving json or plain web view according to the requirement.

Let’s register the macro in any Service Provider, preferably AppServiceProvider. In its boot function, place this snippet.

It checks whether the request wants json data or plain HTML.

Now, in your controller, where you are returning previously view, change it to something like this.

This way, both your web view and your API can be handled at one point.

Major implementation of this idea is found in ajax forms.

I would not recommend doing this. But it gets the job done, almost always.

Everything is awesome.