All posts

Senior Backend Interview: Laravel — the Container, Middleware, Eloquent and the Service Layer

The service container, middleware, Eloquent relationships, why a service layer, and migrations — Laravel answers without reciting the docs.

Marijan Kopčić••2 min read
Senior Backend Interview: Laravel — the Container, Middleware, Eloquent and the Service Layer

Laravel is the framework where it is easiest to hide behind "the framework does it". A senior answer shows you know why it does it and when you would work around it.

The service container

It resolves dependencies — if a constructor asks for an interface, the container knows which implementation to inject. I register bindings in a service provider, so swapping an implementation is a single line.

$this->app->bind(OrderRepository::class, EloquentOrderRepository::class);

Middleware

The layer a request passes through before and after the controller — authentication, rate limiting, logging. Everything that concerns all routes but isn't business logic.

Eloquent relationships

hasOne and hasMany when the foreign key sits on the other side, belongsTo when it is on my side, belongsToMany through a pivot table, morphTo for polymorphic relations.

Why a service layer

So that business logic doesn't live in the controller. The controller takes the request and returns the response, the service does the work. That way the logic can be tested without HTTP and called from the console or from a queue.

final class CreateReservation
{
    public function __construct(private ReservationRepository $reservations) {}

    public function handle(array $data): Reservation
    {
        return $this->reservations->create($data);
    }
}

Migrations

A versioned database schema in code. Every change is a file with up and down, so the database state can be reproduced in any environment. I never change a migration that has already run — I write a new one.

Keep reading