Laravel: Modern PHP Framework

Laravel: Modern PHP Framework in PHP: --- Imagine two ways to open a restaurant. In the first, you rent an empty room and buy every appliance, run the gas and…


The Analogy: The Fully Fitted Commercial Kitchen

Imagine two ways to open a restaurant. In the first, you rent an empty room and buy every appliance, run the gas and water yourself, build the shelving, and wire the lights before you can cook a single dish. In the second, you lease a fully fitted commercial kitchen: the ovens are installed, the plumbing works, the extraction fans run, the prep stations are laid out to a proven plan. You walk in and start cooking. Laravel is that fitted kitchen. Plain PHP is the empty room. A framework is a large body of pre-built, pre-wired machinery so you spend your time on the meal -- your application's actual features -- not on the plumbing.

The fitted kitchen enforces a sensible layout that any trained chef recognises. The walk-in fridge is always in roughly the same place; the pass is where plates go out; the wash-up is by the door. Because the layout follows convention, a new chef is productive on day one without a bespoke map. Laravel works the same way through "convention over configuration": routes live in one known place, controllers in another, database models in another. A developer who knows Laravel can open any Laravel project and immediately know where things are, because the framework insists on a shared structure.

Crucially, the kitchen provides the appliances but does not cook the food. It gives you the oven; you decide the recipe. Laravel supplies routing, a database layer, templating, validation, authentication scaffolding, and a hundred other appliances, but your business logic -- what your app actually does -- is still yours to write. The framework's job is to remove the repetitive, error-prone plumbing that every web app needs, so that two different restaurants sharing the same kitchen brand can still serve completely different menus.

The failure mode is the chef who fights the kitchen. Someone who insists on ripping out the installed ovens to bolt in their own, or who ignores the layout and stores raw fish next to the dessert station, loses every benefit the fitted kitchen offered and often creates a mess that the next chef cannot understand. In Laravel this is the developer who works against the framework's conventions -- bypassing its routing, hand-rolling what it already provides, scattering logic where the framework does not expect it. The framework's power comes from its conventions; abandoning them while still paying the framework's overhead is the worst of both worlds. A framework is leverage only when you work with its grain.


Syntax or Core Structure

The examples in this lesson are deliberately small, plain-PHP illustrations of Laravel's core ideas, so they run and can be verified without installing the framework. Real Laravel is far larger, but the shapes are faithful. The first idea is the front controller: a single entry point that maps an incoming request to a handler.

<?php
declare(strict_types=1);

$routes = [
    'GET /'        => fn() => 'Home',
    'GET /about'   => fn() => 'About us',
    'GET /users/1' => fn() => 'User #1',
];

function handle(array $routes, string $method, string $path): string {
    $key = "$method $path";
    $handler = $routes[$key] ?? null;
    if ($handler === null) {
        return '404 Not Found';
    }
    return $handler();
}

echo handle($routes, 'GET', '/'), "\n";
echo handle($routes, 'GET', '/about'), "\n";
echo handle($routes, 'GET', '/users/1'), "\n";
echo handle($routes, 'GET', '/missing'), "\n";

Output:

Home
About us
User #1
404 Not Found

Every Laravel request enters through a single public/index.php front controller, which hands the request to the router. This miniature captures the essence: a map from a method-and-path key to a handler, with a fallback when nothing matches. Laravel's router adds route parameters, names, groups, and middleware, but the fundamental act -- turn a request into the right handler, or a 404 -- is exactly this.


Technical Depth: The Container, the Lifecycle, and the Ecosystem

The service container

At Laravel's heart is a service container -- an object that knows how to build and supply your application's other objects. You "bind" a name to a factory, and later "resolve" it. A plain binding runs the factory every time; a singleton runs it once and shares the result.

<?php
declare(strict_types=1);

final class Container {
    private array $bindings = [];
    private array $instances = [];
    public function bind(string $id, callable $factory): void {
        $this->bindings[$id] = $factory;
    }
    public function singleton(string $id, callable $factory): void {
        $this->bindings[$id] = function () use ($id, $factory) {
            return $this->instances[$id] ??= $factory($this);
        };
    }
    public function make(string $id): mixed {
        $f = $this->bindings[$id] ?? throw new RuntimeException("unbound: $id");
        return $f($this);
    }
}

$c = new Container();
$c->bind('mailer', fn() => new stdClass());
$c->singleton('db', fn() => new stdClass());

$m1 = $c->make('mailer');
$m2 = $c->make('mailer');
echo 'bind gives same object? ', ($m1 === $m2 ? 'yes' : 'no'), "\n";

$d1 = $c->make('db');
$d2 = $c->make('db');
echo 'singleton gives same object? ', ($d1 === $d2 ? 'yes' : 'no'), "\n";

Output:

bind gives same object? no
singleton gives same object? yes

The bind for mailer runs its factory on each make, so the two objects are distinct -- no. The singleton for db caches the first result with the ??= operator and returns it thereafter, so both resolutions are the same object -- yes. Laravel's real container adds automatic dependency resolution, reading a class's constructor type hints and building what it needs, but this bind-and-resolve core is the whole idea.

The request lifecycle

Understanding the order of events demystifies the framework. A request flows through fixed stages, each a place where Laravel does specific work.

StageWhat happens
Entrypublic/index.php boots the framework
ContainerThe application container is created and services registered
MiddlewareRequest passes through global and route middleware
RoutingThe router matches the URL to a controller action
ControllerYour code runs, often using models and services
ResponseA response travels back out through middleware to the browser

Each later lesson in this module drills into one stage: routing and controllers, the Eloquent models the controller uses, the Blade templates it renders, the validation that guards input, and the middleware and authentication that wrap the whole request.

The ecosystem

Laravel is more than the framework code. It ships with an ecosystem: Artisan (a command-line tool for generating code and running tasks), Composer (the dependency manager that installs Laravel and its packages), Eloquent (the ORM), Blade (the template engine), and a large library of first-party packages for queues, mail, authentication, and testing. This breadth is why teams choose it: common needs already have a supported, conventional solution, so you rarely reinvent infrastructure.

Facades: static-looking access to container services

Laravel exposes many services through "facades" -- classes you call statically, like Cache::get(...) or Log::info(...) -- yet the work is done by a real instance the container holds. The static call is a thin proxy, forwarded via __callStatic to the underlying object, which keeps call sites terse while remaining swappable underneath.

<?php
declare(strict_types=1);

final class Logger {
    private array $lines = [];
    public function write(string $msg): void { $this->lines[] = $msg; }
    public function count(): int { return count($this->lines); }
}

final class Log {
    private static ?Logger $instance = null;
    public static function swap(Logger $l): void { self::$instance = $l; }
    public static function __callStatic(string $name, array $args): mixed {
        $target = self::$instance ??= new Logger();
        return $target->$name(...$args);
    }
}

Log::swap(new Logger());
Log::write('boot');
Log::write('request handled');
echo 'log lines: ', Log::count(), "\n";

Output:

log lines: 2

Calling Log::write and Log::count looks static, but __callStatic forwards each call to the real Logger instance behind the facade, which accumulates the two lines. Because the instance is swappable via swap, a test can substitute a fake logger and assert against it, exactly as Laravel's facades can be faked in tests. The convenience of a static call is preserved without truly hard-coding a global, which is the tension facades are designed to resolve -- and also why some developers prefer plain injection, a trade-off worth understanding.


Real World Example: A Mini Application in the Laravel Shape

To see the pieces cooperate, here is a tiny application that wires a container, a router, and a controller together -- the same collaboration Laravel performs on every request, stripped to its essence. The container builds the controller, the router matches the path and dispatches to it, and the controller returns a response.

<?php
declare(strict_types=1);

final class Container {
    private array $b = [];
    public function bind(string $id, callable $f): void { $this->b[$id] = $f; }
    public function make(string $id): mixed {
        return ($this->b[$id] ?? throw new RuntimeException("unbound: $id"))($this);
    }
}

final class GreetController {
    public function show(string $name): string {
        return "Hello, $name";
    }
}

final class Router {
    private array $routes = [];
    public function get(string $path, array $action): void {
        $this->routes["GET $path"] = $action;
    }
    public function dispatch(Container $c, string $method, string $path, array $params = []): string {
        $action = $this->routes["$method $path"] ?? null;
        if ($action === null) {
            return '404';
        }
        [$class, $verb] = $action;
        $controller = $c->make($class);
        return $controller->$verb(...$params);
    }
}

$c = new Container();
$c->bind(GreetController::class, fn() => new GreetController());

$router = new Router();
$router->get('/greet', [GreetController::class, 'show']);

echo $router->dispatch($c, 'GET', '/greet', ['Ada']), "\n";
echo $router->dispatch($c, 'GET', '/greet', ['Ben']), "\n";
echo $router->dispatch($c, 'GET', '/nope'), "\n";

Output:

Hello, Ada
Hello, Ben
404

The router registers /greet against the [GreetController::class, 'show'] action, a controller-and-method pair exactly like Laravel's route definitions. On dispatch, the router looks up the action, asks the container to build the controller, and calls the method with the parameters -- greeting Ada and Ben, and returning 404 for an unregistered path. This container-resolves-controller, router-dispatches flow is precisely what Laravel automates, only with auto-wired dependencies and a great deal more machinery around it.

The design flaw is that this illustration, like any simplification, hides the hard parts that make a real framework valuable -- and that is the honest caution to carry into the rest of the module. The miniature has no middleware pipeline, so there is nowhere to enforce authentication or rate limiting; it resolves controllers by explicit binding rather than reading constructor type hints, so it cannot auto-wire a controller's dependencies; and it has no error handling, configuration, or response abstraction. Mistaking the miniature for the real thing leads to under-estimating why the framework exists: the plumbing it removes is genuinely intricate, and the value is precisely in the parts too large to show in a runnable snippet. Treat these illustrations as a mental model of the shape, not as a substitute for learning the actual framework, whose documentation and conventions are where real Laravel work happens.


Common Mistakes

  1. Fighting the conventions. Bypassing the router, scattering logic where the framework does not expect it, or hand-rolling what Laravel provides loses the framework's leverage. Work with its grain.
  1. Putting business logic in controllers. A controller should coordinate, not compute. Push real logic into services and models so it is testable and reusable.
  1. Ignoring the container. Instantiating dependencies with new everywhere defeats dependency injection. Bind and resolve through the container so wiring is centralised and swappable.
  1. Treating a singleton like a fresh instance. Registering something as a singleton and then expecting per-request state to reset leads to leaked state. Know which bindings are shared.
  1. Skipping Artisan. Writing boilerplate by hand that artisan make: would generate wastes time and invites inconsistency. Learn the generators.
  1. Editing vendor code. Changing files under vendor/ is overwritten on the next composer update. Extend or configure instead, never patch the dependency in place.
  1. Misunderstanding the lifecycle. Not knowing when middleware runs versus when the controller runs leads to guarding the wrong stage. Learn the request lifecycle order.
  1. Committing secrets. Hard-coding credentials instead of using the .env file and config leaks secrets into version control. Keep environment-specific values in .env.
  1. Assuming the framework is your application. Laravel provides plumbing, not features. Confusing "I installed Laravel" with "I built the app" underestimates the domain work still to do.

Best Practices

  • Follow Laravel's conventions for file placement and naming, so any Laravel developer can navigate your project instantly.
  • Keep controllers thin -- coordinate the request and delegate real work to services and models.
  • Register dependencies in the container and inject them, rather than constructing collaborators with new throughout the code.
  • Use Artisan generators to scaffold controllers, models, and migrations consistently instead of writing boilerplate by hand.
  • Store environment-specific configuration and secrets in .env, and read them through config, never hard-coded in source.
  • Learn the request lifecycle so you guard, transform, or short-circuit requests at the correct stage.
  • Treat vendor/ as read-only, extending behaviour through configuration, service providers, and your own classes.
  • Lean on the ecosystem -- queues, mail, auth scaffolding, testing helpers -- rather than reinventing infrastructure the framework already supplies.

Practice Exercises

  1. Build a plain-PHP route table mapping several method-and-path keys to closures, and a handle function that returns the matched handler's result or a 404. Test three hits and one miss.
  1. Implement a small container with bind, singleton, and make, and demonstrate that a bound factory yields distinct objects while a singleton yields the same one.
  1. Write out the request lifecycle stages in order, and for each name one concrete responsibility Laravel handles there, from entry through response.
  1. Extend the mini application so the router supports a fallback controller action for unmatched paths, and show it invoked for a path you did not register.