Mihir Bhende
Mihir Bhende

Reputation: 9045

Laravel add custom method for all eloquent models

I am looking for a way to add few custom methods which will be used in all models. I can imagine 3 ways of doing it :

  1. Adding custom method to main Eloquent's Model.php class file(I want to avoid doing this as this is a core file)
  2. Creating a custom model class with required custom methods, which will extend to eloquent's Model class and all the models in the project will extend to custom model class.
  3. Adding a trait which will have my methods and include it inside all models

However, I want to do it more efficiently and best way possible. Is their any other way to do it?

PS I am using laravel 5.2 as its an old project.

Upvotes: 2

Views: 619

Answers (1)

Mr. Pyramid
Mr. Pyramid

Reputation: 3935

Based on the comment discussion and adding my experience in Laravel I would suggest you to go either with #2 or #3 approach as @ceejayoz have specified in the comments

first one is definitely a bad approach as you need to modify the core which is not at all a good practice. Second and third are both good approaches.

But, before that you need to check your requirements if literally all models (including any future ones your app will ever have) need the extra functionality, however you can use traits for all models.

If I have the choice probably I will go for traits over custom models as traits are relatively simple then custom models

Upvotes: 1

Related Questions