Bhavin Shah Bhavin Shah - 3 months ago 19x
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.


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

Thank You.


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);