0

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
0

4 Answers 4

1

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]
Sign up to request clarification or add additional context in comments.

2 Comments

pluck returns a Collection
>>> $email = $external['email'] PHP Notice: Undefined index: email in /home/vagrant/code/{domain_name_censored}/vendor/laravel/framework/src/Illuminate/Support/Collection.php on line 1290 >>>
0

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'];

1 Comment

This works thanks... However, how do you return all emails too?
0

Try this

$external = collect(App\External::all()->pluck('data'))->pluck('email')->all();

Comments

0

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'];
    });

2 Comments

This works thanks... However, how do you return all emails too?
to do so you can get all() and map() result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.