snake

Eloquent mutators & accessors are handy feature that can simplify your high level code and hide some data-related logic in the model.

However, it is pretty common to misuse them and soon regret it.

Let’s take a look and see where we can go wrong…

So far, so good. It’s nice and easy, doesn’t seem to be a problem, and now we can we can easily output *full name* in view, or wherever we need:

Now, imagine you follow this path, and keep adding accessors like this to you models, for sake of data presentation. As it becomes habit, we’re tempted to use accessors for all kind of stuff until one day we do this to, say, a *Product* model:

simple scenario – show product’s price:

obviously we want it to be nice and well-formatted, so why not use an accessor:

The price in our view is now formatted and we’re good to go for the next task, until we realize that BOOOM – we just broke our ecommerce site into pieces…

It’s likely, that somewhere in the app we have something between the lines of:

but now, all the (gross) prices became 0 so we’re in trouble, unless we spot the issue before our client (or we do things the right way, have tests yada yada yada, but that’s different story..):

 

The moral of the story is, that data handling and its presentation should not go into the same bucket. And the model is that bucket – instead of creating accessors, traits or god knows what for this task, better use decorator (like) pattern where you can do all the necessary work for preparing your data to be displayed in your view, without touching actual values anywhere else.

This brings much more that just safety, for example you can easily handle translations, transformations and other tedious tasks, that definitely don’t belongs to the data handling layer.

If you’re looking for a ready-to-use package, that can do it for you, or simply would like to grasp the idea, go check this one: laravel-auto-presenter by Shawn McCool and friends

It's only fair to share...Tweet about this on TwitterShare on RedditPin on PinterestShare on FacebookShare on Google+

Related Post

20 Eloquent tricks – more Recently I stumbled upon interesting article by Povilas Korop on laravel-news 20 eloquent tips and tricks. First of all thanks for sharing your knowle...
A story about Laravel Resources Leo is a brilliant developer. He turns every idea into code in no time. He's prepared for any task thrown at him and dives into coding straight away, ...
How to add custom casters in Laravel tinker I made a series about psysh and Laravel's tinker - powerful REPL where you can play with your whole application. ICYMI check it out here: tinker li...
Too much M4g1c will kill you (or at least bite you... So, as you know, I'm a big fan of Laravel, in particular Eloquent is my favourite. The beauty and value of both is a lot of conventions and magic...