Abhijith
Abhijith

Reputation: 411

JSON Encoded data not accessible

I queried the data from database using a Model.

echo $user = User::whereRaw('username = ? and password = ?', array($username,$password))->get();

The output is in JSON format

[{"id":1,"name":"Abhijith","username":"abhi","created_at":"2014-07-31 20:07:35","updated_at":"2014-07-31 20:07:35"}]

But when I try to echo a single field, I get an index not found error.

echo $user->id; //Gives an error saying the index is not found

Upvotes: 0

Views: 83

Answers (1)

AbraCadaver
AbraCadaver

Reputation: 78984

You need to get in the habit of looking at the structure and not assuming. Also, you need to json_decode the string. Then use print_r to see the structure:

$result = json_decode($user);
echo $result[0]->id;

Or (PHP >= 5.4.0 I think):

echo json_decode($user)[0]->id;

Upvotes: 2

Related Questions