Reputation: 831
Hi i am new to PHP and Laravel, my question is how does this whole thing with eloquent works.
What i mean is when i create a model class and a migration with it, i can just use it like that Model->title = "value";
. How does eloquent models figure out table structure and create member variables within the class.
class Post extends Model
{
public function author()
{
return $this->author;
}
}
Is there some kind of reflection stuff going on with Schemas created in migrations ? or some polymorphic magic ?
Upvotes: 0
Views: 398
Reputation: 50491
They are not member variables. Eloquent doesn't know anything about your schema until it actually queries it. So when the model is retrieved from the database, the selected fields are stored in an array called $attributes
.
There is a magic method for objects named __get
that is being used here. This is called when you try to access a non accessible property of the object. Since there are no public member variables with the name of the field it calls __get
. When you look into that method defined on Model you will see it calls getAttribute
.
Just like there is a __get
there is a __set
magic method for setting non accessible properties. On the model __set
calls setAttribute
.
I hope this gives you some enlightenment on this subject. There are more things in play like relationships and accessors/mutators but this is the basic idea.
PHP.net Manual - OOP - Property Overloading __get
__set
Laravel Framework Github - Illuminate\Database\Eloquent\Model
__get
Laravel Framework Github - Illuminate\Database\Eloquent\Model
__set
Laravel Framework Github - Illuminate\Database\Eloquent\Concerns\HasAttributes
getAttribute
Laravel Framework Github - Illuminate\Database\Eloquent\Concerns\HasAttributes
setAttribute
Upvotes: 2