Skip to content

Instantly share code, notes, and snippets.

@IceTimux

IceTimux/zr64t.md

Last active Nov 25, 2020
Embed
What would you like to do?

~Laravel | On accessors with the same name as the database field


If you have $product->price and you want to format it, do not create the accessor function getPriceAttribute() on your model. Why?

Consider this example.

I have a OneToMany relation between Event and Major models as events belongsTo Major and Major hasMany events.

// in some file

public function getMajorAttribute()
{
  // does some formatting
  return $formattedValue;
}

. . .

// in some other file

return Event::find(1)->major; // gets picked up by getMajorAttribute 
return Major::find(1)->events; // because there is no accessor set, just goes to relationship

So what is happening here is that the accessor method is getting used instead of our Eloquent relationship.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment