Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Laravel services, should we inject model classes or just use them with imports?

I started refactoring a Laravel app that has most of its logic in controllers, into services. I do not plan on using the repository pattern.

When using a model in a service class which is the better way?

  1. Importing the model and using it directly eg.:

    MEDevel.com: Open-source for Healthcare and Education

    Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

    Visit Medevel

    User::all()

  2. Injecting it in the constructor of the service and using it like this:

    $this->userModel->all()

>Solution :

Both methods are valid, but in many cases, injecting the model provides a good balance of flexibility and maintainability, especially as your application grows.
Ultimately, the choice depends on your specific needs and the complexity of your application. If you’re unsure, dependency injection can offer more long-term benefits.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading