0

I have a code User::find(0) that will find and return data of first user in database type object. I can set the value like $user->name = "Name 1" or $user->name = "Name 2".

"Cannot use object of type stdClass as array"

I made a new variable like $teacher = (object) [] and $teacher = new \stdClass. I can set the value like $teacher->name = "Teacher 1". But, I will get above error if I set it like $teacher['name'] = "Teacher 1".

Expected type "object". Found string[].

So, I tried to make $teacher = array() and $teacher = []; I can set the value like $teacher['name'] = "Teacher 1", but I will get above error if I set it with $teacher->name = "Teacher 2".

So, I'm confused why User::find(0) object can be set using '->' and '[]'. I'm still learning to use documentation. I spent alot of time but still can't find it even in another website. Can you you tell me how can I make the same object like User::find(0) that I can set the value using '->' and '[]'?

1 Answer 1

1

This is because your User model extends the Laravel base model Illuminate\Database\Eloquent\Model.php. The base model implements the ArrayAccess interface which allows accessing objects as arrays.

You can read more on this in the docs from php itself https://www.php.net/manual/en/class.arrayaccess.php

Sign up to request clarification or add additional context in comments.

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.