Laravel - Return HTML or JSON in same Method

2

I'm starting with Laravel, seeing from the rails, where to return a JSON I simply put .json in the url, obviously the return handling is on 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 for json, to have only one for both and in the view I could determine what would be the return.

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

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

Hugs

    
asked by anonymous 13.03.2016 / 21:21

1 answer

3

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

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

Think about 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 access the url, you will see view . If you use $.ajax , it will return JSON .

Update :

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

    
14.03.2016 / 17:43