Laravel Services Pattern

Starting out Laravel I heard a lot of good advice, particularly on Laracast. But others are confusing, particularly on MVC. The common question is where do you put business logic. You’ll hear that you want to keep your controllers skinny and models thin. What the hell?

Using a service layer is the answer if you dig deeper. But service layers are not exactly covered in the Laravel documentation nor part of any guides and learning modules. But here’s what I understand so far.

Put your extra business logic in a Service class and import it into your controller.

Here’s a good excerpt from Travis Britz on SO.

Services, on the other hand, are an easy way to encapsulate the logic around a component, and they may do more than one thing… Consider if you didn’t store books by inserting them into your database, but instead by posting to an external API. All of these requests share logic for authenticating to the external web service (like adding headers to requests), and your BookRepository class can encapsulate that re-usable logic. You can use this service class inside of scheduled artisan commands, web controllers, api controllers, jobs, middleware, etc. — without repeating code.

P. Ellul shows what this might look like.

What about creating a Services folder under app/, and use Controller dependency injection.

MyService.php


namespace App\Services;

use App\Models\Bar;

class MyService
{
    public function foo(Bar $bar)
    {
       // do things
    }
}

MyController.php



namespace App\Http\Controllers;

use App\Services\MyService;
use App\Models\Bar;

class MyController extends Controller
{
    protected $myService;

    public function __construct(MyService $myService)
    {
        $this->myService = $myService;
    }

    public function handleRequest(Bar $bar)
    {
        $this->myService->foo($bar);
    }
}

Leave a Comment