Laravel return json or view Laravel return json or view json json

Laravel return json or view


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.


In Laravel 5.x, to implement both capabilities like sending data for AJAX or JSON request and otherwise returning view template for others, all you have to do is check $request->ajax() or $request->isJson().

public function controllerMethod(Request $request){   if ($request->ajax() || $request->isJson()) {      //Get data from your Model or whatever      return $data;   } else {      return view('myView.index');   }}