Eloquent has a really nice feature that most people don't use at all. It's the ability to create getters and setters for the different attributes. In computer science the propper name for this methods are Accessor and Mutator, being the former used to return a variable value and the latter to control changes to a variable.

Implementing a getter or setter method in Laravel 4 is really easy, just create the method with the name get[Name]Attribute or set[Name]Attribute respectively, being [Name] the name of the attribute. The convention here is that the method must be in camelCase even though the database columns are in snake_case.

Keep in mind that both methods receive the value as a parameter, so make sure to receive the parameter that is being passed over when defining it. getAgeAttribute($value) or setAgeAttribute($value) respectively.

These methods are extremely useful when wanting to return a value in a certain format. The most common case that I've seen myself using these methods is when I want to specify the attributes in a certain way before converting them to JSON. For example, If we have a boolean attribute in a class called selected, depending on our database, this attribute could be mapped to an int value in the database, being 1 true and 0 false. If we want to retrieve the value always as a boolean value rather than an int, we can define a accessor that casts our value to a boolean.

public function getSelectedAttribute($value){
    return (bool) $value;

In the same fashion, if we have an attribute that always needs some type of formatting before saving it to the database we can create a mutator. A nice example could be when assigning a password to an user instance.

$user = new User();
$user->password = 'test'; // we want 'test' to be hashed

Then by writting this method in the class definition we will be transforming the value before assigning it.

public function setPasswordAttribute($value){
    $this->attributes['password'] = Hash::make($value);

So, there you go, having these methods implemented could save you from doing a cast from a variable everytime that you want it in another data type.

Comments? Something wrong in the post? or just want to contact me? Send me a tweet to @gpopoteur on twitter.