In Laravel, Accessors and Mutators allow you to manipulate data when you store or read it. The Mutator allows you to alter data when it is stored, and the Accessor allows you to alter data when it is fetched from a database. These can be pretty useful if used correctly. For example, if you want to retrieve an image that was stored with a relative path in the form of a URL, i.e. A field stored in the user_avatar
field as /path/to/image.jpg
can become https://www.website.com/path/to/image.jpg
.
To define an Accessor, create a getAccessorNameAttribute
method in your Model where AccessorName
is the "studly" cased name of the column you want to change. When we retrieve the user_avatar
attribute, Eloquent will automatically make use of the Accessor.
As can be seen below, we pass the original value of the user_avatar
attribute, and manipulate it to return in URL form. When the user_avatar
attribute is accessed on a model instance, it will now return this new URL value.
To define a Mutator, create a setMutatorNameAttribute
method in your Model where MutatorName
is the "studly" cased name of the column you want to change. When we set the user_avatar
attribute, Eloquent will automatically make use of the Mutator.
As can be seen below, we pass the original value of the user_avatar
attribute, and manipulate it to convert the value to a URL. When the user_avatar
attribute is set on a model instance, it will now set this new URL value.