Architecture

Understanding MVC Architecture

Mayur Dabhi
Mayur Dabhi
April 20, 2026
14 min read

You open OrderController.php to change one shipping rule and find a 400-line store() method that calculates discounts, sends emails, and builds half the HTML in strings. The same rule is also copied into an Artisan command, slightly differently. Nobody wants to touch it, and there are no tests because the logic can only be reached through an HTTP request.

That mess usually isn't caused by the framework. Laravel, Rails, Django, ASP.NET Core and Spring MVC all hand you the Model-View-Controller structure for free. The trouble starts when people know the folder names but not what each layer is actually supposed to own. This post goes through where MVC came from, what belongs in the model, view and controller, the anti-patterns I run into most, and when it's worth adding service and repository layers on top.

Why This Matters

Fat controllers and untestable code are usually a symptom of blurry layer boundaries, not of a bad framework. Moving logic out of a controller early is cheap. Doing it after a year of features piled on top is a real project.

The Origin of MVC

Trygve Reenskaug came up with MVC in 1979 while working on Smalltalk at Xerox PARC. The problem he had was practical: a graphical user interface needed a way to separate the data it displayed from the widgets used to display it, while keeping a mediating layer that translated user gestures into meaningful actions on data.

The core idea is simple: data and presentation change for different reasons. Your schema changes when business rules change. Your UI changes when someone redesigns the page. If the two are tangled together, every UI tweak risks breaking business logic and every schema change drags the templates along with it.

Web frameworks later bent the pattern to fit the request-response cycle. The "View" became an HTTP response instead of a live widget, and the "Controller" handled one incoming request instead of a stream of mouse events. Struts, Rails and the PHP frameworks that followed made this the default shape of server-side web apps for the last two decades or so.

Browser HTTP Request Router Dispatches Controller Orchestrates the request Model Business logic Data access View HTML / JSON Template rendering DB SQL route calls queries renders HTTP Response (HTML / JSON)

The MVC request-response cycle in a web application

The Three Layers in Depth

Most people can name the three layers. The harder part is deciding, line by line, which one a piece of code belongs in.

The Model: Your Application's Brain

If you think of a model as "the class that maps to a table", you'll end up with business rules scattered everywhere else. The model layer is where your domain lives: the rules, calculations and state transitions that make an order an order. A good model knows nothing about HTTP, HTML, or how its data will be shown.

The Model layer typically includes:

app/Models/Order.php (model with business logic)
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
    protected $fillable = ['user_id', 'status', 'total'];

    const STATUS_PENDING   = 'pending';
    const STATUS_PAID      = 'paid';
    const STATUS_SHIPPED   = 'shipped';
    const STATUS_CANCELLED = 'cancelled';

    // --- Relationships ---

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function items()
    {
        return $this->hasMany(OrderItem::class);
    }

    // --- Business Rules (belong in Model, NOT Controller) ---

    public function canBeShipped(): bool
    {
        return $this->status === self::STATUS_PAID;
    }

    public function canBeCancelled(): bool
    {
        return in_array($this->status, [self::STATUS_PENDING, self::STATUS_PAID]);
    }

    public function markAsShipped(): void
    {
        if (! $this->canBeShipped()) {
            throw new \DomainException("Order #{$this->id} cannot be shipped in status: {$this->status}");
        }

        $this->update(['status' => self::STATUS_SHIPPED]);
    }

    // --- Computed attribute (presentation hint, but still domain knowledge) ---

    public function getFormattedTotalAttribute(): string
    {
        return '$' . number_format($this->total / 100, 2);
    }
}
Fat Model, Thin Controller

Keep business logic in models (or service classes), not controllers. If your controller has an if/else that encodes a business decision, move it to the model. The controller's job is to call the right model methods and hand the result to a view.

The View: Pure Presentation

A view takes the data it's given and turns it into HTML, JSON, XML, CSV or whatever format the client needs. That's all. It shouldn't calculate discounts, decide whether the user is allowed to see something, or query the database.

Signs your View layer is doing too much:

resources/views/orders/show.blade.php (clean view)
@extends('layouts.app')

@section('content')
<div class="order-detail">
    <h1>Order #{{ $order->id }}</h1>
    <p class="status status--{{ $order->status }}">{{ ucfirst($order->status) }}</p>
    <p>Total: {{ $order->formatted_total }}</p>

    {{-- $canShip is a boolean passed from Controller, not decided here --}}
    @if($canShip)
        <form action="{{ route('orders.ship', $order) }}" method="POST">
            @csrf
            <button type="submit">Mark as Shipped</button>
        </form>
    @endif

    <ul>
        @foreach($order->items as $item)
            <li>{{ $item->product->name }} × {{ $item->quantity }}</li>
        @endforeach
    </ul>
</div>
@endsection

The Controller: The Traffic Cop

A controller takes an HTTP request, works out what needs to happen, hands that work to models or services, and passes the result to a view. It coordinates. Once it starts calculating prices, formatting emails or running long conditional workflows, it's doing someone else's job.

app/Http/Controllers/OrderController.php (thin controller)
<?php

namespace App\Http\Controllers;

use App\Models\Order;
use Illuminate\Http\Request;

class OrderController extends Controller
{
    public function show(Order $order)
    {
        // Controller only orchestrates: prepare data for the view
        return view('orders.show', [
            'order'   => $order,
            'canShip' => $order->canBeShipped(), // Business rule lives in Model
        ]);
    }

    public function ship(Order $order)
    {
        // Delegate the actual work to the Model
        $order->markAsShipped();

        return redirect()
            ->route('orders.show', $order)
            ->with('success', 'Order has been marked as shipped.');
    }

    public function cancel(Order $order)
    {
        if (! $order->canBeCancelled()) {
            abort(422, 'This order cannot be cancelled.');
        }

        $order->update(['status' => Order::STATUS_CANCELLED]);

        return redirect()->route('orders.index')
            ->with('success', 'Order cancelled.');
    }
}
Watch the Exception

If someone double-clicks "Mark as Shipped", the second request hits markAsShipped() on an already shipped order and throws a DomainException. Laravel doesn't know what that means, so the user gets a 500 page and your error tracker gets noise. Either check canBeShipped() in the controller and return a 422 like cancel() does, or map DomainException to a 422 response in your exception handler.

MVC Request Flow: Step by Step

Here's what happens when a user visits https://example.com/orders/42:

1

HTTP Request Arrives

The web server (Nginx/Apache) receives a GET request for /orders/42 and forwards it to the PHP application's entry point (public/index.php).

2

Router Dispatches

The framework's router matches the URL and method against registered route definitions and resolves which controller method handles it: OrderController@show with id=42.

3

Middleware Pipeline

Before reaching the controller, the request passes through middleware (authentication checks, CSRF verification, rate limiting, logging). If any middleware rejects the request, the controller is never invoked.

4

Controller Runs

The controller retrieves the Order model (via route model binding or manual query), calls any needed business methods on it, and prepares a data array for the view.

5

Model Queries the Database

The ORM translates model calls into SQL queries, executes them, and returns hydrated model objects or collections back to the controller.

6

View Renders the Response

The template engine (Blade, Twig, ERB) merges the data from the controller with the HTML template. The rendered HTML string is sent back as the HTTP response body.

MVC vs Other Patterns

MVC isn't the only way to split things up. These are the alternatives you'll run into most, and where each one tends to fit better.

Pattern Key Difference from MVC Best For
MVC Classic server-side, Controller returns a View directly Traditional server-rendered web apps (Laravel, Rails)
MVP (Model-View-Presenter) Presenter mediates all interaction; View is fully passive Desktop GUIs, Android apps, highly testable UIs
MVVM (Model-View-ViewModel) ViewModel exposes observable state; View binds to it Data-binding UI frameworks like WPF, Angular and Vue
ADR (Action-Domain-Responder) One class per action; Responder separate from Domain REST APIs where controllers become bloated
Hexagonal (Ports & Adapters) Core domain isolated from all infrastructure via ports Large enterprise systems, DDD-driven codebases

Common MVC Anti-Patterns

These are the mistakes I see most often in MVC codebases, roughly in order of how much pain they cause.

Fat Controllers

A controller method that runs queries, does business math, sends emails, processes files and then returns a view. This is by far the most common violation. Every line of business logic in a controller is logic that cannot be independently tested and cannot be reused from another entry point (e.g., a CLI command or queue job).

Anti-pattern vs Correct approach
// ❌ Fat Controller: business logic crammed in controller
public function checkout(Request $request)
{
    $cart = Cart::find($request->cart_id);
    $total = 0;
    foreach ($cart->items as $item) {
        $total += $item->price * $item->quantity;
    }
    if ($cart->user->hasPromoCode()) {
        $total -= $total * 0.1; // 10% discount
    }
    if ($total > 10000) {
        $shippingFee = 0;
    } else {
        $shippingFee = 500;
    }
    $order = Order::create([...]);
    Mail::to($cart->user)->send(new OrderConfirmation($order));
    return view('checkout.success', compact('order'));
}

// ✅ Thin Controller: delegates to a service/model
public function checkout(Request $request, CheckoutService $checkout)
{
    $order = $checkout->processCart(
        Cart::find($request->cart_id),
        $request->validated()
    );

    return view('checkout.success', compact('order'));
}

Anemic Models

The opposite problem. Models are plain data bags with getters and setters, and all the business logic lives in services or controllers. You get procedural code dressed up as objects, and you can't tell what states an entity is allowed to be in by reading its class.

Views That Query the Database

A User::where(...)->get() inside a Blade template mixes the data layer into presentation. You can't cache the response cleanly or change where the data comes from without editing templates.

The N+1 Problem Warning

A view that touches a lazy-loaded relationship inside a loop fires one query per row. Eager-load in the controller (for example Order::with('items.product')->find($id)) so the view only renders data that's already fetched. In Laravel you can add Model::preventLazyLoading(! app()->isProduction()); to AppServiceProvider::boot(). Locally, any lazy load then throws a LazyLoadingViolationException naming the model and relationship, which catches these before they reach production.

Extending MVC with Service and Repository Layers

Once an app grows past a handful of CRUD screens, three layers start to feel tight. Two extra layers are common.

The Service Layer

A service class (also called an application service or use case) wraps one business operation that touches several models, calls external APIs, dispatches events or queues jobs. The controller calls the service and the service coordinates the models. Controllers stay thin, and models don't have to know about mail, queues or payment gateways.

app/Services/CheckoutService.php
<?php

namespace App\Services;

use App\Models\Cart;
use App\Models\Order;
use App\Mail\OrderConfirmation;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\DB;

class CheckoutService
{
    public function processCart(Cart $cart, array $paymentData): Order
    {
        return DB::transaction(function () use ($cart, $paymentData) {
            // 1. Calculate total (domain logic stays in models)
            $total = $cart->calculateTotal();

            // 2. Create the order
            $order = Order::create([
                'user_id' => $cart->user_id,
                'total'   => $total,
                'status'  => Order::STATUS_PENDING,
            ]);

            // 3. Copy cart items to order items
            foreach ($cart->items as $item) {
                $order->items()->create([
                    'product_id' => $item->product_id,
                    'quantity'   => $item->quantity,
                    'price'      => $item->price,
                ]);
            }

            // 4. Clear cart
            $cart->clear();

            // 5. Send confirmation email
            Mail::to($cart->user)->send(new OrderConfirmation($order));

            return $order;
        });
    }
}

One thing to watch in that example: the email is sent inside DB::transaction(). If the commit fails after send() runs, the customer gets a confirmation for an order that doesn't exist. And if you switch to Mail::queue(), a fast queue worker can pick the job up before the transaction commits and fail to find the order. Moving the send after the transaction returns fixes both. If you queue the mail, calling afterCommit() on the mailable also works.

The Repository Layer

A repository sits between the model and the database and gives you a collection-like interface for persistence. It earns its keep when you genuinely need to swap the data source for some queries (say, MySQL to Elasticsearch for search) or want to test data-access logic without a real database. In a typical Laravel app, wrapping Eloquent in a repository that just forwards calls adds files without adding much.

Request HTTP Controller Thin Service Use Cases Model Domain Repository Data access DB View Extended MVC with Service + Repository Layers

MVC with service and repository layers added

MVC Across Different Frameworks

Each framework names and arranges things a little differently, but the split is the same. Here's the same order page in four of them.

Laravel gives every layer a default home. Routing in routes/web.php, Controllers in app/Http/Controllers/, Models in app/Models/, Views in resources/views/.

// Route
Route::get('/orders/{order}', [OrderController::class, 'show']);

// Controller
public function show(Order $order) {
    return view('orders.show', ['order' => $order]);
}

// Model (Eloquent)
class Order extends Model {
    public function items() { return $this->hasMany(OrderItem::class); }
}

// View (Blade)
// resources/views/orders/show.blade.php

Express.js doesn't enforce MVC, but the pattern is commonly applied by organizing code into routes, controllers, and models (Mongoose/Sequelize).

// routes/orders.js (Router)
router.get('/:id', orderController.show);

// controllers/orderController.js (Controller)
exports.show = async (req, res) => {
  const order = await Order.findById(req.params.id)
                           .populate('items');
  res.render('orders/show', { order });
};

// models/Order.js (Model)
const orderSchema = new mongoose.Schema({
  userId: { type: ObjectId, ref: 'User' },
  status: String,
  total: Number,
});
module.exports = mongoose.model('Order', orderSchema);

Django calls itself MTV (Model-Template-View) but it maps directly to MVC: Model = Model, Template = View, View = Controller.

# models.py (Model)
class Order(models.Model):
    user    = models.ForeignKey(User, on_delete=models.CASCADE)
    status  = models.CharField(max_length=20)
    total   = models.IntegerField()

# views.py (Controller in MVC terms)
def order_detail(request, pk):
    order = get_object_or_404(Order, pk=pk)
    return render(request, 'orders/show.html', {'order': order})

# urls.py (Router)
path('orders/<int:pk>/', views.order_detail, name='order-detail'),

# templates/orders/show.html (View in MVC terms)
<h1>Order #{{ order.id }}</h1>

Ruby on Rails is the framework that made MVC the default for web apps. With convention over configuration, the file structure is the MVC structure.

# config/routes.rb (Router)
resources :orders, only: [:show, :update]

# app/controllers/orders_controller.rb (Controller)
class OrdersController < ApplicationController
  def show
    @order = Order.find(params[:id])
  end
end

# app/models/order.rb (Model)
class Order < ApplicationRecord
  belongs_to :user
  has_many   :order_items

  def can_be_shipped?
    status == 'paid'
  end
end

# app/views/orders/show.html.erb (View)
<h1>Order #<%= @order.id %></h1>

Testing in an MVC Application

Clean layers make testing a lot easier, because each layer can be tested on its own:

Layer Test Type What to Assert Needs DB?
Model Unit Test Business rules, state transitions, calculations Yes (or mocked)
Controller Feature / Integration Test HTTP status codes, redirects, view data, session Usually yes
View Browser / E2E Test Rendered HTML, UI interactions Yes (seeded)
Service Unit Test Correct method calls, return values, exceptions No (mock models)
tests/Unit/OrderTest.php (model unit test)
<?php

namespace Tests\Unit;

use App\Models\Order;
use PHPUnit\Framework\TestCase;

class OrderTest extends TestCase
{
    public function test_paid_order_can_be_shipped(): void
    {
        $order = new Order(['status' => Order::STATUS_PAID]);
        $this->assertTrue($order->canBeShipped());
    }

    public function test_pending_order_cannot_be_shipped(): void
    {
        $order = new Order(['status' => Order::STATUS_PENDING]);
        $this->assertFalse($order->canBeShipped());
    }

    public function test_shipping_a_non_paid_order_throws_exception(): void
    {
        $this->expectException(\DomainException::class);

        $order = new Order(['status' => Order::STATUS_PENDING, 'id' => 1]);
        $order->markAsShipped();
    }
}

MVC Best Practices Checklist

  • Controllers: No business logic. No database queries beyond simple model lookups. No email sending. Just orchestrate and pass data to a view.
  • Models: Encode domain rules as methods, not just data properties. Validate state transitions. Use relationships to express domain connections.
  • Views: No database queries. No business calculations. Receive prepared, pre-calculated data from the controller.
  • Services: Extract complex multi-step operations that span multiple models or require external calls.
  • Repositories: Abstract data access if you have complex query logic or need to test without a real DB.
  • Routing: Keep route files readable. Group by feature and apply shared middleware through route groups.
  • Testing: Unit-test model business rules. Feature-test controller endpoints. Avoid testing the same logic at multiple layers.

How Far I'd Take MVC (and When I Wouldn't)

For a server-rendered app with forms, CRUD screens and some business rules, plain MVC with fat models and thin controllers is usually enough. I'd only add a service class when an operation spans several models or talks to the outside world (payments, mail, queues). I'd only add repositories when there's a real second data source or a real testing need, not because a tutorial had them.

Where MVC Is the Wrong Shape

  • Tiny APIs and scripts: a webhook receiver with three endpoints doesn't need a model and view per resource. A route closure or a single-action controller is fine.
  • Rich client-side UIs: if React or Vue renders everything, the server-side "View" shrinks to JSON resources and most of the interesting UI structure lives in the frontend, with its own patterns.
  • Very large domains: when one Eloquent model is carrying billing, shipping and reporting rules at once, the model itself becomes the fat class. That's the point to look at service layers, domain modules or hexagonal architecture.
  • Heavy reporting queries: forcing complex aggregate SQL through models and repositories often makes it harder to read. A dedicated query class returning plain arrays is more honest.

A quick check you can run today: open your largest controller. If a method is longer than your screen, or you'd have to fake an HTTP request just to test a business rule in it, that logic belongs in a model or a service.

MVC Architecture Patterns Design Patterns Web Development Software Architecture
Mayur Dabhi

Mayur Dabhi

Full Stack Developer with 5+ years of experience building scalable web applications with Laravel, React, and Node.js.