Dev Notes

Software Development Resources by David Egan.

Laravel Accessors - Format or Prepare Data for Access

David Egan

Laravel Accessors are Model methods that allow Eloquent attributes to be formatted or processed when they are retrieved.

To set up an Accessor, 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:


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

An accessor that takes a string saved in the post_title column and converts it to uppercase in the Eloquent attribute would look like this:

public function getPostTitleAttribute($title)
      $this->attributes['post_title'] = strtoupper($title);

The method receives the value of the attribute, and is automatically called when the value of the attribute is retrieved.

In the view for this example:

@foreach($posts as $post)

…titles will be capitailsed.

When the attribute is accessed, it will be in uppercase. The string stored in the database remains unchanged.


Laravel Docs: Accessors & Mutators

comments powered by Disqus