Laravel return json or view

api, json, laravel, laravel-4

Solution

I suggest you to create your application as an api.

Foreach page, you need two controllers. Each controller use a different route (in your case, one route ending by .json, and one without).

The json controller return data in json form. The "normal" controller call the corresponding json route, deserialize the json, then pass the resulting array to the view.

This way, you've got a standardized api (and maintained, because your own app use it) available, as well as a "normal" website.

More information: Consuming my own Laravel API

Edit: Maybe it's doable with a filter, but I'm not sure about that and I don't have time to try it myself right now.

Problem

I'm developing an API where if the user specifies the action with `.json` as a suffix (e.g. `admin/users.json`), they get the response in the return of json, otherwise they get a regular html View. Some actions may not have a json response, in which case they would just return a html View. Does anyone have advice on how this can be implemented cleanly? I was hoping it could be achieved via the routing.

Original source

Related problems