Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel return json or view

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.

like image 994
David Wadge Avatar asked Aug 21 '13 11:08

David Wadge


2 Answers

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.

like image 166
Atrakeur Avatar answered Oct 05 '22 07:10

Atrakeur


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');
   }
}
like image 41
Andy Avatar answered Oct 05 '22 08:10

Andy