Bhavin Shah Bhavin Shah - 5 months ago 28
JSON Question

How to get one or certain number of columns in json format in Laravel 5.2?

Below is my code.

$users = DB::table('users')->get();

return json_encode($users);


I want to get only one column or specific number of columns in JSON format.

I am getting this output.

[{"user_id":70,"email_id":"xyz@abc.com","name":"XYZ"}]

I want only user_id as JSON format data.
How can I get it?

Thank You.

Answer

Try this

$users = DB::table('users')->select('user_id')->get();
return json_encode($users);

or this

$users = DB::table('users')->get(['user_id']);
return json_encode($users);

Also it would probably make your life easier to use User model class so you could then do this

$users = User::select('user_id')->get();
return json_encode($users);

or this

$users = User::get(['user_id']);
return json_encode($users);