Return Laravel json API

Asked

Viewed 954 times

2

I’m having a problem following, I made a API and I get one back array:

"id": 1,
"email": "[email protected]",
"senha": "lucas123",
"created_at": "2018-02-15 16:48:12",
 "updated_at": "2018-02-15 16:48:12"`

and would like you to return only 3 fields id,email and senha

Method:

public function index() 
{ 
    $contas = login::all(); 
    return response()->json(['contas'=>$contas], 200); 
}
  • Please enter the code for controller, the image makes it very difficult.

  • 1

    Opa yes! I will send only the index method can be ?

2 answers

4


Just select with the method select what you need:

login::select('id', 'email', 'senha')->get();

Complete code:

public function index() 
{ 
    $contas = login::select('id', 'email', 'senha')->get();
    return response()->json(['contas'=>$contas], 200); 
}

Reference: Laravel - Selects

1

For you to be able to return an object and not an array, it is enough:

public function index() 
{ 
    $contas = login::select('id', 'email', 'senha')->get();
    return response()->json(Arr::first($contas), 200); 
}

Note that in the case is used a Helper of Laravel itself that takes the first item of the answer coming from select. So when we pass this to Response the return will be an object and not an array anymore.

To use the helpers of Laravel add:

use Illuminate\Support\Arr;

IMPORTANT:

Arr::first()

As informed returns the first item of an array, if you need to return a Collection, or more than one item as an object in the same response the informed process will not work.

Browser other questions tagged

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