MVC (Laravel) Where to Add Logic

Where to put logic instead of controller in Laravel 8

First of all:

Create a folder named Services in app.

Put your service there.

Give it a namespace: App\Services

use it with use App\Services\YourService

at some point, run a composer dump-autoload, to register (if it doesn't work by default).

Then: MVC (which is a general pattern) - has the principle of Fat Models / Slim Controllers.
IN the old days (Codeigniter) - most of us used to put the logic in the Model. The model was a bit more lightweight than the Eloquent models now.

When things got complicated we moved the logic to a Library (in library folder).

Now, a Service is just a class. You just instantiate it, inject whatever you need and do the job.

Where to put business logic when you don't have a specified model for that feature? Laravel

In this case, I would personally recommend using a Service. A service class is essentially for common functionality that you may repeat across multiple controllers. The Service Layer is a design pattern that will help you to abstract your shared logic to a common service i.e. our new Service Class.

So in your instance, you could have a Service class such as ExcelValidator and then use something like the following to structure your approach.

<?php

namespace App/Services;

class ExcelValidatorService
{

public function validate($file)
{
// our validate logic
}

}

And then in your controllers or models, you can call the ExcelValidator service to implement your repeated validate logic.

Where I must contain business logic of my application?

It's down to preferences. As long as you are using the correct standards, you should be fine!

So in Laravel, I use Models strictly for database operations. I also create a folder called Services and another folder called Hydrators

My services in the service folder handles the business logic e.g grabbing data from the models and any logical operations. My hydrators take the data and sort it in the way I want the data to be presented to the view.

Both my services and hydrators take on the Single Responsibility Principle as this allows me to reuse the same code elsewhere to avoid code duplication!

My controllers are just an entry point to the back end and only do two things; call the services and stitch the ones needed together and return a result (a result could be anything from JSON to a view with data).

This is just my personal way of doing things. Others may have a different way.



Related Topics



Leave a reply



Submit