Return array of properties in the Laravel

Asked

Viewed 262 times

1

I created a function in the controller that returns the users where the user condition is 1.

Currently it is returning in json all the data of this user.

How can I return only user emails?

I tried something like:

public function avisarAnjos(Request $request){
    $usuariosAnjos = User::where('usuario_anjo', '1')->get();
    return response()->json($usuariosAnjos.email);
}

and:

public function avisarAnjos(Request $request){
    $usuariosAnjos = User::where('usuario_anjo', '1')->get();
    return response()->json($usuariosAnjos->email);
}

and

public function avisarAnjos(Request $request){
    $usuariosAnjos = User::where('usuario_anjo', '1')->get();
    return response()->json($usuariosAnjos['email']);
}
  • 1

    the answer to helped solve your problem?

2 answers

2


To return only one field use the method select (or even selectRaw`) and bring only the field(s) (s) on the return of the Builder, example:

public function avisarAnjos(Request $request)
{
    $usuariosAnjos = User::where('usuario_anjo', '1')->select('email')->get();
    return response()->json($usuariosAnjos);
}

this example will generate a : SELECT email FROM users WHERE usuario_anjo = ?, and the result only the mailing list as per filter.

References:

0

public function avisarAnjos(Request $request)
{
    $usuariosAnjos = User::where(['usuario_anjo'=>'1'])->get(['email']);
    return response()->json($usuariosAnjos);
}

Browser other questions tagged

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