Search code examples
phplaravelcode-organization

In Laravel, where should I store this code?


Using Laravel to develop a web app I'm facing some unclearity where to put some code.

I have a User-like model that gets its data from another database. I can only read in that database but that's fine. Fields like name, city and so are very inconsistently stored in the database. For example sometimes a name is fully capitalized, other times it's not. So I've created a method formatAsName which currently resides in my UserController.

But the thing is, every time a user-like object is retreived from the database I'd like to use this method for some columns (like name and city). Should this code be stored in the controller, or does it belong to the model?

Side question: is there a way to tell Laravel to perform a callback when executing a query for this model? Ortherwise I have to manually write some of the core Model-methods. This is no problem to do since there's limited interaction (only retrieval) but if it's supported that would be the best way.

Thanks for your time.


Solution

  • You can define your method in model also and there are many methods in laravel, you can find more help here for your code guidance :- HERE