Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where does non-model logic go in Laravel [closed]

Tags:

php

laravel

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?

like image 684
randombits Avatar asked Nov 26 '22 22:11

randombits


1 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();
    }
}
like image 53
Egretos Avatar answered Nov 29 '22 03:11

Egretos