0

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
3
  • 1
    are you getting an actual string of json data? If so you would need to json_decode it to turn it into a php object that you can access or else it is just a string. Commented Jul 31, 2014 at 21:35
  • 1
    You have to decode the json object like here with json_decode Commented Jul 31, 2014 at 21:35
  • echo $user[0]->id; Look at the object, it makes sense. Taking away this superfluous up-vote. Commented Jul 31, 2014 at 21:42

1 Answer 1

2

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

3 Comments

Got it. Thank you. All I had to do was echo $result[0]->id;
Note: you didn't need to json_decode it. It's only JSON because it was echo'd (it has a magic method for when it is used as a string), its actually an object that can naturally be accessed with $user[0]->id
@Someguy123: Good to know. I'm not a laravel guy.

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.