You need a presenter layer. I've had very good luck with this:
https://github.com/ShawnMcCool/laravel-auto-presenter
Enjoy super clean views!
The best Presenter package out there - in my opinion - is 'Easy View Presenters' by the author of Laracasts, Jeffrey Way. He did a lesson on how to build view presenters from scratch: https://laracasts.com/lessons/view-presenters-from-scratch (paid content).
Yeah I saw that. I'd say the result is the same with both of them, just depends how you want the code to look like in your views:
Shawn's
$user->fullName
Jeff's
$user->present()->fullName
Thanks a lot! Really, presenter is what I need.
Is model accessors what you are looking for ?
public function getRatingAttribute($value)
{
return number_format($value, 2);
}
mcraz said:
Is model accessors what you are looking for ?
Not exactly, but I've caught the idea, thanks!
I mean' it's perfect for my example, but I have other needs as well.
I only see one more layer abstraction using the Presenters instead of model accesor, I don't see more advantages
Seems that the difference is just the context in how they are used. For example if we were using the models property to do math in our application logic we would probably want it unchanged from the value in the database, say in the database it has six decimals. Using a presenter layer would not affect it here. But if we use the model accessor the value we get will be changed according to whatever logic we put in our getting accessor (such as format to 2 decimals), in a view context or not. Would love to hear from the experts on this...
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community