TutsPlus.com: Eloquent Mutators and Accessors in Laravel
On the TutsPlus.com site they've posted a tutorial for the Laravel users (well, Eloquent users) out there showing the use of mutators and accessors in this ORM package.
In this article, we'll go through mutators and accessors of the Eloquent ORM in the Laravel web framework. After the introduction, we'll go through a handful of examples to understand these concepts.
In Laravel, mutators and accessors allow you to alter data before it's saved to and fetched from a database. To be specific, the mutator allows you to alter data before it's saved to a database. On the other hand, the accessor allows you to alter data after it's fetched from a database. In fact, the Laravel model is the central place where you can create mutator and accessor methods. And of course, it's nice to have all your modifications in a single place rather than scattered over different places.
The tutorial starts with the creation of a simple "Post" model to use in the examples via the
artisan command. It also includes the full code to flesh out the class to define a mutator and accessor for the "name" property. It then talks through what these two methods do and how they're called automatically when the property is accessed/updated. It's then put to use in a controller showing each of them in use to work with the
published_at date value.