Marcin Cezary
Marcin Cezary

Reputation: 13

Where to put logic instead of controller in Laravel 8

I want to know where to put the logic of the application instead of inside a controller. According to the MVC pattern, it shouldn't be written in the controller, but nothing seems good to put it in. For example, the model is for communication with the DB, views are for showing given data in different orders, but I have to count, calculate and draw correct data from a given big scope. I read about events, listeners, and service providers, but all instructions say to put other stuff in there. I tried manually creating some Services directory classes, but the controller doesn't seem to see it, and I got the following error.

Error Class 'App\Services\MyService' not found

app\Services\MyServices.php

use App\Models\Lotto;
use App\Models\Duzylotek;

class MyService
{
    public function suggested() {
       //
    }
}

app\Http\Controllers\MyController.php

namespace App\Http\Controllers;

use App\Services\MyService;

class MyController extends Controller
{
    public function countnext()
    {
        (new MyService)->suggested();
    }
}

Upvotes: 1

Views: 1464

Answers (1)

Frederik B.
Frederik B.

Reputation: 211

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.

Upvotes: 1

Related Questions