Skip to main content

Layered architecture in Laravel

Laravel does not require any structure beyond MVC, but large projects usually add a Service layer and a Repository layer to separate business logic from HTTP and from the database. This page describes each layer, compares it with Spring Boot, and applies it to an e-commerce system.

info

Setup, the service container, migrations, auth, and the rest are already in the Laravel Handbook. This page focuses on how the code is organized.

The layers​

LayerRoleResponsibilityPrinciple
ControllerReceive the HTTP request, return the HTTP responseOrchestrate the flow, take data that is already validated (Form Request), call the Service, return a View or JSONKeep the controller "thin", with no business logic
ServiceWrap the business logicComplex processes (placing an order, promotions), coordinate several Repositories, call outside services (payment, shipping)Where business logic "lives", reusable from a controller, a command, or a job
RepositoryThe abstraction between the business logic and the data sourceA consistent interface (find, create, update), wrap complex Eloquent queries, easy to mock in testsOptional — useful on a large project, overkill for simple CRUD
ModelRepresents one table (Active Record)Relationships (hasMany, belongsTo), $fillable/$guarded, accessors and mutators, local scopes, basic CRUDHolds only logic tied to its own data

Example: placing an order​

// app/Http/Controllers/OrderController.php
class OrderController extends Controller
{
public function __construct(private OrderService $orders) {}

public function store(StoreOrderRequest $request)
{
$order = $this->orders->place($request->user(), $request->validated());

return redirect()->route('orders.show', $order);
}
}

// app/Services/OrderService.php
class OrderService
{
public function __construct(
private OrderRepository $orders,
private ProductRepository $products,
) {}

public function place(User $user, array $data): Order
{
$order = DB::transaction(function () use ($user, $data) {
$order = $this->orders->createWithItems($user, $data['items']);
$this->products->decrementStock($data['items']);

return $order;
});

OrderPlaced::dispatch($order); // send the email, notifications… through a listener

return $order;
}
}

The Service Container injects the dependencies through the constructor on its own. If the Repository is an interface, bind it in a Service Provider:

// app/Providers/AppServiceProvider.php
public function register(): void
{
$this->app->bind(OrderRepository::class, EloquentOrderRepository::class);
}

Request-handling flow​

  1. public/index.php — the only entry point; it loads Composer's autoloader and creates the application.
  2. Bootstrap — loads .env and config, then registers and boots the Service Providers (Router, Database, and the application's providers).
  3. HTTP Kernel — wraps the request as a Request object and passes it through the global middleware.
  4. Router — finds the route that matches the URI and method, and runs the middleware attached to that route.
  5. Controller / Closure — handles the request, and calls a Service or Model.
  6. Response — a View or JSON; it goes back through the middleware chain, then is sent to the client.

Step by step: Application Lifecycle.

Comparison with Spring Boot​

PieceLaravelSpring Boot
RoutingCentral route files (routes/web.php, routes/api.php), fluent syntax, Route Model Binding, Resource ControllerAnnotations on the controller (@GetMapping, @PostMapping), spread across each controller
MiddlewareA simple PHP class, registered in bootstrap/app.php (->withMiddleware(), Laravel 11+) or app/Http/Kernel.php (Laravel 10 and earlier)Servlet Filter and HandlerInterceptor; more layers, but more complex
Dependency InjectionService Container, auto-resolves from the type-hint (zero config), bindings in a Service ProviderApplicationContext, based on annotations (@Service, constructor injection)
ORMEloquent — Active Record; the model is tied to the table ($user->save())Spring Data JPA — Repository pattern; the entity is a POJO, queries go through a repository interface
ValidationA Form Request packages both validation and authorizationBean Validation (Jakarta Validation) with annotations on the DTO (@NotNull, @Size)
TemplateBlade — syntax close to PHP, compiled and cachedThymeleaf — "natural templating" (valid HTML), th:* attributes

Applied: e-commerce​

  1. The Controller receives the request from the checkout page; the data is already validated by a Form Request.
  2. OrderService gets the cart, creates Order and OrderItem through OrderRepository, and decrements stock through ProductRepository — all inside one transaction.
  3. The service fires the OrderPlaced event; the SendOrderConfirmationEmail listener (implements ShouldQueue) sends the email through the queue.
  4. The controller returns the order-confirmation view.

Suggested packages

  • Order status: spatie/laravel-model-states (pending → processing → shipped…)
  • Payments: laravel/cashier (Stripe, official), stripe/stripe-php, srmklive/laravel-paypal
  • Cart: gloudemans/shoppingcart, or build your own with a carts table / session

Good practices​

PracticeWhyExample
Eager loadingAvoid an N+1 query when walking a relationshipOrder::with('items.product')->get()
Queue long-running tasksSending email or processing images should not slow the responseclass SendOrderConfirmationEmail implements ShouldQueue
Validation through a Form RequestPackages validation and authorization, and keeps the controller smallphp artisan make:request StoreOrderRequest
Events and ListenersPull side tasks (notifications, stock) out of the main flowOrderPlaced::dispatch($order)
Cache on purposeCut an expensive query, or data that rarely changesCache::remember('categories', 3600, fn () => Category::all())
Write testsKeep quality and stability when you refactorA feature test for the order flow, a unit test for the Service
tip

Turn on Model::preventLazyLoading(! app()->isProduction()); in AppServiceProvider::boot() so Laravel errors immediately when there is lazy loading (a sign of N+1) in dev.