test
test

Reputation: 18198

Laravel - Get specific array in JSON encoded database column

Let's say I have a table called Posts with these columns:

-- uid (int)
-- title (str)
-- body (text)
-- data (json)

and in one row, inside the data column, I have a JSON encoded response like so:

[{
    "title": "Blue",
    "points": 0,
    "tags": [{
        "type": "Comedy",
        "uid": 45
    }]
}, {
    "title": "Green Orange",
    "points": 2,
    "tags": [{
        "type": "Horror",
        "uid": 1
    }]
}]

All of that is json_encode into one database column.

How can I make it so that I can get the Green Orange into a variable?

I have tried:

$post = Post::where('id', $id)->first();

$data = json_decode($post->data);

return $data[0];

But that just gives me: The Response content must be a string or object implementing __toString(), \"object\" given.

Upvotes: 0

Views: 2173

Answers (2)

user6679664
user6679664

Reputation:

you need to access the title field in the second object of array.

return $data[1]->title;

Upvotes: 0

Luca C.
Luca C.

Reputation: 12594

You are accessing the full object, instead you need its field:

$post = Post::where('id', $id)->first();//$post = Post::find($id); would be better

$data = json_decode($post->data);

return $data[1]->title;//note than Green Orange is in the second object of the array, so not index 0 but 1

Upvotes: 2

Related Questions