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.
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
I know you already got your answer, but I still want to give you a tip.
A good approach for this case is to use the Repository Pattern. Doing that you can create Presenters and Transformers for your model and define how you want your models to be retrieved
public function transform(User $model)
{
return [
'name' => strtolower($model->name),
'city' => strtolower($model->city),
'created_at' => Carbon::parse($model->created_at)->format('d-m-Y'),
'updated_at' => Carbon::parse($model->updated_at)->format('d-m-Y'),
];
}
Sorry but I don't have any source/material to send you about this pattern, but surely you can find it on google. You can check my github if you want and take a look on this repo which have an example https://github.com/cbcaio/base-laravel