Laravel - Return HTML or JSON in the same Method

Asked

Viewed 849 times

2

I’m starting with Laravel, seeing from Rails, where to return a JSON I just put . json in the url, the return processing is obviously in the Controller.

My question is how to do something like Laravel. I would like, instead of creating a method to return html and another one to json, to have only one for both and in the view I could determine what the return would be.

  public function lista(){
    $produtos = 'select na tabela';
    return view('produtos.listagem')->withProdutos($produtos);
  }

The above code returns htmlby default, you would choose the return type?

Hugs

  • http://stackoverflow.com/questions/32573457/laravel-5-return-html-or-json-depending-on-route

1 answer

3


My solution to this would be to detect the header of the requisition.

If required XHTTPRequest, we return JSON. If not, we return HTML.

Think of this idea:

Route::get('usuarios/listar', function (Request $request)
{

     $usuarios = Usuario::all();


     if ($request->ajax()) {
         response()->json(compact('usuarios'));
     }

     return view('usuarios.listar', compact('usuarios'));
});

So if you go to the url, you’ll see the view. If you use a $.ajax, will return the JSON.

Updating:

There is a method which, in my view, is better than $request->ajax(). This method is called $request->wantsJson(). It basically identifies whether the request sent a header saying what response JSON is accepted.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.