Accessors are what you are looking for. As the name states Accessors will be called whenever you try to access that certain property on the eloquent model.
<?php
class MyModel extends Eloquent {
public function getImageAttribute($value)
{
if(is_null($value))
return 'default_image.jpg';
return $value;
}
}
Update:
Just for clarification reasons: When you try to access attributes that do not exist on a class, PHP invokes the __get()
magic method (if it does exist), instead of complaining.
Eloquent works exactely the same way. When __call()
is invoked (remember, attributes you call on an eloquent model do not really exist) laravel will give you the value of that field from your database. The trick comes in here.
When the __get()
method is called on an eloquent model. Eloquent will call it's getAttribute()
method which grabs the attribute but checks if an accessor exists beforehand (in laravel source accessors are called get mutators). You can see it here.
If that's the case laravel calls the mutateAttribute()
method on the given key. The mutateAttribute()
will then eventually call the getXAttribute
(source) where X
is the name of the attribute being accessed.
That's the whole trick behind the magic that's going, and again shows how well structured laravels source is.