Dev Notes

Software Development Resources by David Egan.

Laravel Mutators


Laravel
David Egan

Laravel mutators are Model methods that process data in some way before it is stored in the database.

Potential use cases:

  • Capitalising names before saving
  • Title-casing titles
  • Slugifying slugs
  • Change date strings to Carbon objects
  • Hashing passwords
  • JSON encoding (possible in MySQL 5.7.8, coming soon in MariaDB)

To set up a Mutator, add a suitable method in the Model class. The database column is determined by the method name, which hence needs to be in a certain format:

set{ColumnName}Attribute

Note that the column name needs to be written in StudlyCaps (PascalCase) - the first letter of each sub-word (including the first) is capitalised.

A mutator that converts a string to title case, saved in the post_title column would look like this:

<?php
public function setPostTitleAttribute($title)
    {
      $this->attributes['post_title'] = ucwords($title);
    }

Note that the method doesn’t return anything - it just directly accesses the atribute and “mutates” the value.

References


comments powered by Disqus