Bhavin Shah Bhavin Shah - 1 year ago 102
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.

Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download