If I want an Eloquent Model class to have setters and getters for the sake of implementing an interface does the following approach make sense or is there a 'laravel' approach to the problem
class MyClass extends Model implements someContract
{
public function setFoo($value) {
parent::__set('foo', $value);
return $this;
}
public function getFoo() {
return parent::__get('foo');
}
}
The above Model which has function setPasswordAttribute will save the password with bcrypted value (which is basically called Setters or Mutators), And the function getFullNameAttribute will append first name and last name retrived from database (which is called Getters or Accessors)
Accessors and mutators allow you to format Eloquent attributes when retrieving them from a model or setting their value. For example, you may want to use the Laravel encrypter to encrypt a value while it is stored in the database, and then automatically decrypt the attribute when you access it on an Eloquent model.
From Laravel Documentation: Attribute Casting The $casts property on your model provides a convenient method of converting attributes to common data types. The $casts property should be an array where the key is the name of the attribute being cast and the value is the type you wish to cast the column to.
PHP does not have getter and setter syntax. It provides subclassed or magic methods to allow "hooking" and overriding the property lookup process, as pointed out by Dave.
You are probably looking for accessors (getters) and mutators (setters).
Example of an accessor (getter) in Laravel:
public function getFirstNameAttribute($value)
{
return ucfirst($value);
}
Example of a mutator (setter) in Laravel:
public function setFirstNameAttribute($value)
{
$this->attributes['first_name'] = strtolower($value);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With