Dev Notes

Various Cheat Sheets and Resources by David Egan/Carawebs.

Laravel Accessors - Format or Prepare Data for Access


Laravel
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:

get{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.

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:

<?php
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)
  <h2>{{$post->title}}</h2>
@endforeach

…titles will be capitailsed.

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

References

Laravel Docs: Accessors & Mutators


comments powered by Disqus