29.07.2016 Views

laravel-5

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Eloquent: Mutators 474<br />

.<br />

12 * @param string $value<br />

13 * @return string<br />

14 */<br />

15 public function getFirstNameAttribute($value)<br />

16 {<br />

17 return ucfirst($value);<br />

18 }<br />

19 }<br />

As you can see, the original value of the column is passed to the accessor, allowing you to manipulate<br />

and return the value. To access the value of the mutator, you may simply access the first_name<br />

attribute:<br />

.<br />

1 $user = App\User::find(1);<br />

2<br />

3 $firstName = $user->first_name;<br />

Defining A Mutator<br />

To define a mutator, define a setFooAttribute method on your model where Foo is the “camel”<br />

cased name of the column you wish to access. So, again, let’s define a mutator for the first_-<br />

name attribute. This mutator will be automatically called when we attempt to set the value of the<br />

first_name attribute on the model:<br />

.<br />

1

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!