Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Setters and Getters to Laravel Model

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');
  }
}
like image 557
Gazzer Avatar asked Oct 31 '16 06:10

Gazzer


People also ask

What is setter and getter in laravel?

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)

What is accessors and mutators in laravel?

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.

What is $cast in laravel?

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.

Does PHP have getters and setters?

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.


1 Answers

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);
}
like image 169
Alexey Mezenin Avatar answered Oct 05 '22 12:10

Alexey Mezenin