Getter & Setter Methods in Eloquent

As I mentioned before, Laravel offers this 2 methods to handle how information is displayed or changed before insert.

The rules are simple: you declare them by¬†appending “set_” ¬†or “get_” to the intended attribute’s name.

Setter example and usage

To format a date:

public function get_date_start()

   return date('M d, Y', $this->get_attribute('date_start')));


Now everytime you use $object->date_start, it will be formatted accordingly.

Getter example and usage

To encrypt a password before inserting in the database:

public function set_password($password) 
    $this->set_attribute('password', Hash::make($password)); 


How to user MySQL functions with eloquent and fluent

Both Eloquent ORM and Fluent query builder are wonderful tools, but, sometimes you want more, you may for example want to concatenate 2 fields (for presentation purposes Eloquent provides Getter & Setter Methods, but that’s another story for another time).


 return self::get( array( 'id', 'CONCAT(first_name, " ", last_name)' ) );

Won’t work, to insert MySQL functions you have to use DB::raw() method:

 return self::get( array( 'id', DB::raw('CONCAT(first_name, " ", last_name)') ) );