Reputation: 345
For example, I have JSON stored in a Row of a database called 'data'
External.php (model) - casting 'data' to an array:
protected $casts = [
'data' => 'array',
];
I can access it using Tinker with this commmand:
$external = App\External::first()->pluck('data');
This returns
Illuminate\Support\Collection {#3384
all: [
[
"id" => 17566616456845,
"name" => "#1008",
"note" => "",
"tags" => "",
"test" => false,
"email" => "[email protected]",
"phone" => null,
...
..
.
How do I access the "email" or "id" from that collection? How do I modify the tinker eloquent command to get the "id" or "email"?
$external = App\External::all()->pluck('data')->'email'
T_STRING or T_VARIABLE or '{' or '$' on line 1> Exception with message 'Property [email] does not exist on this> PHP Parse error: Syntax error, unexpected T_CONSTANT_ENCAPSED_STRING, expecting
Getting warmer:
>>> $external = App\External::pluck('data')->get('email')
=> null
Upvotes: 0
Views: 1279
Reputation: 4499
You don't have to use pluck()
.
if you want to access email from the data of an External.
$email = App\External::first()->data['email'];
UPDATE
to get all the emails.
$emails = App\External::all()
->map(function($external) {
return $external->data['email'];
});
Upvotes: 0
Reputation: 41
Try this
$external = collect(App\External::all()->pluck('data'))->pluck('email')->all();
Upvotes: 0
Reputation: 50491
If you are just trying to get the data for one record use the cast attribute as an array:
// one External record
$external = App\External::first();
$email = $external->data['email'];
$id = $external->data['id'];
Upvotes: 0
Reputation: 354
pluck() method returns array. So if you want to access 'email' you must use.
$external = App\External::first()->pluck('data');
$email = $external['email']; // [email protected]
Upvotes: 1