11.6 Setters and Getters
Setters are handy little methods that allow us to format our new model data in a certain way
when it is assigned. Let’s take a look at a code snippet.
3 public function set_password($password)
5 $this->set_attribute('hashed_password', Hash::make($password));
We create a method with the name of the setter prefixed with set_, and pass it a variable which
will receive the field value. Now we can use set_attribute() to set a field to its new value.
This will allow us to modify the passed value anyway we like. The snippet above will cause the
hashed_password field to be updated with a hashed version of the supplied value when we call :
3 $user->password = "secret_panda_ninja";
Getters are the exact opposite. They can be used to adjust a value when it is being read. For
3 public function get_panda_name()
5 return 'Panda'.$this->get_attribute('name');
Now if our name is Dayle we can use..1 <?php
3 echo $user->panda_name;
which would give ‘PandaDayle’.
In the next chapter we will take a look at Laravel’s simple events system.