Laravel return json or view

10,101

Solution 1

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.

Solution 2

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');
   }
}
Share:
10,101
David Wadge
Author by

David Wadge

Updated on July 25, 2022

Comments

  • David Wadge
    David Wadge almost 2 years

    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.

  • David Wadge
    David Wadge over 10 years
    This sounds sensible, thanks. Looks like this was also discussed on the laravel github: github.com/laravel/framework/issues/788
  • Ru Chern Chong
    Ru Chern Chong over 6 years
    This seemed to be a good way handle between JSON responses for API and view for HTML. However, is this even a good practice? It does not feel clean to me.
  • Andy
    Andy over 6 years
    Well, it is quite clean. It is a good fit in scenario where you need to reuse the existing controller logic and routes from Frontend for SPA like interface and also at the same time have capability to support rendering views in Blade templates from server side. Otherwise what do you propose ? Adding new routes and duplicating the business logic for fetching the same data for AJAX request?