Where does non-model logic go in Laravel

Viewed 279

I have a Laravel 7.x project. One of my controller methods is starting to get beefy with logic that does not belong in a model. It is code that can be re-used by other controllers. I would like to abstract it and make it available to the controller as a helper function. In the Laravel world, where would such logic go? Is it a Provider? Where in the documentation should I be looking to move this controller logic out so any other controller or possibly even models in the future can invoke said function?

2 Answers

I use Services for tings like this. My services contains business logic, and one service always handle single model. As example my simple service:

<?php

namespace App\Services;

use App\Models\Company;


class CompanyService
{
    public function create(array $data) {

        // some another business logic here

        return Company::create($data)
    }

}

Then i can use this service very easy with dependency injection inside Controllers:

<?php

namespace App\Http\Controllers;

use App\Models\Company\Company;
use App\Services\CompanyService;

final class CompanyController extends Controller
{
    /** @var CompanyService */
    private $companyService;

    public function __construct(CompanyService $companyService)
    {
        $this->companyService = $companyService;
        parent::__construct();
    }

    public Function store($request) {
        $company = $this->companyService->create( $request->validated() );
    
        return $company->toArray();
    }
}
Related