03.12.2015 Views

laravel4cookbook

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

API 135<br />

1 public function setNameAttribute($value)<br />

2 {<br />

3 $clean = preg_replace("/\W/", "", $value);<br />

4 $this->attributes["name"] = $clean;<br />

5 }<br />

6<br />

7 public function getDescriptionAttribute()<br />

8 {<br />

9 return trim($this->attributes["description"]);<br />

10 }<br />

.<br />

This was extracted from app/models/Event.php.<br />

You can catch values, before they hit the database, by creating public set*Attribute() methods. These<br />

should transform the $value in some way and commit the change to the internal $attributes array.<br />

You can also catch values, before they are returned, by creating get*Attribute() methods.<br />

In the case of these methods; I am removing all non-word characters from the name value, before it<br />

hits the database; and trimming the description before it’s returned by the property accessor. Getters<br />

are also called by the toArray() and toJson() methods which transform model instances into either<br />

arrays or JSON strings.<br />

You can also add attributes to models by creating accessors and mutators for them, and mentioning<br />

them in the $appends property:<br />

1 protected $appends = ["hasCategories", "hasSponsors"];<br />

2<br />

3 public function getHasCategoriesAttribute()<br />

4 {<br />

5 $hasCategories = $this->categories()->count() > 0;<br />

6 return $this->attributes["hasCategories"] = $hasCategories;<br />

7 }<br />

8<br />

9 public function getHasSponsorsAttribute()<br />

10 {<br />

11 $hasSponsors = $this->sponsors()->count() > 0;<br />

12 return $this->attributes["hasSponsors"] = $hasSponsors;<br />

13 }

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

Saved successfully!

Ooh no, something went wrong!