Nitish Kumar
Nitish Kumar

Reputation: 6276

Use collection with json_decode object in Laravel

I'm having a data set which is coming through request in my Laravel 6 application, I want to convert this to collection but it is not working out:

$request_status = json_decode($request->status);

$data = collect($request_status)->pluck('id');

dd($data);

This is giving me output of null;

When I do dd($request->status):

"[{"id":3,"type":"Awarded","name":"Awarded"}]"

No change happens in the data, if I do dd($data) I get:

Collection {#791 ▼
  #items: array:1 [▼
    0 => null
  ]
}

I tried doing json_decode($request->status, true) but no luck.

Upvotes: 2

Views: 2964

Answers (2)

TheBurgerShot
TheBurgerShot

Reputation: 1616

If you dd $request_status it returns

"[{"id":3,"type":"Awarded","name":"Awarded"}]"

as a string? Makes sense that the pluck('id') doesn't work then. If so, make sure that returns an array and it'll work.

When I try

$request_status = json_decode('[{"id":3,"type":"Awarded","name":"Awarded"}]');

$data = collect($request_status)->pluck('id');

dd($data);

it returns

Illuminate\Support\Collection^ {#631
  #items: array:1 [
    0 => 3
  ]
}

Upvotes: 1

Prashant Deshmukh.....
Prashant Deshmukh.....

Reputation: 2292

Not sure about correctness but, I have tried something

$request_status = json_decode($request->status,1);

$data = collect([$request_status])->pluck('id')->first();

dd($data);

Upvotes: 0

Related Questions