0

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.

3
  • 2
    what is the output of dd($data) ? Commented Dec 15, 2017 at 16:31
  • 1
    json_decodeprovides by default \StdClass use this to retrieve an array json_decode($post->data, true); And access properties with $data[0]['title'] Commented Dec 15, 2017 at 16:32
  • 1
    although irrelevant to your question, I would recommend $post = Post::find($id); Commented Dec 15, 2017 at 16:33

2 Answers 2

2

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

Comments

0

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

return $data[1]->title;

Comments

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.