Mohammad Sheraz
Mohammad Sheraz

Reputation: 11

Encode Json and get a value from it in laravel

json:

[
   {"student":"a","relation":"son","id":"74"},
   {"student":"b","relation":"son","id":"75"}
]

I want to get the value of each id in this json.(ie 74 and 75) This json is from a column called relation from user table.

I am working with laravel.

Upvotes: 1

Views: 3506

Answers (1)

Alexey Mezenin
Alexey Mezenin

Reputation: 163978

Use json_decode() to convert JSON to an array and collect() to convert it to a collection. Then use pluck() to get all IDs.

$ids = collect(json_decode($json, true))->pluck('id');

Or use array_pluck():

$ids = array_pluck(json_decode($json, true), 'id');

If you want to get IDs from the query, use pluck() instead of get():

$users = User::where('role', 'parent')->pluck('id'); 

Upvotes: 1

Related Questions