Module 2: Laravel 12 Core

Architecture, Routing, and Dependency Injection

Request Lifecycle

Understanding how Laravel handles a request is crucial for senior developers.

  1. Entry Point: public/index.php loads the Composer autoloader and retrieves the application instance.
  2. Kernel: The request is sent to the HTTP Kernel (or Console Kernel). This is where middleware runs.
  3. Service Providers: The core of the bootstrapping process. All service providers are registered (register method) and then booted (boot method).
  4. Routing: The router dispatches the request to a route or controller.
  5. Response: The controller returns a response, which flows back through middleware to the client.

Advanced Routing

Laravel 11+ simplified the directory structure, moving routes to routes/web.php and routes/console.php by default. API routes are opt-in.

Route Groups & Middleware

use App\Http\Controllers\OrderController;

Route::middleware(['auth', 'verified'])->group(function () {
    Route::prefix('orders')->name('orders.')->group(function () {
        Route::get('/', [OrderController::class, 'index'])->name('index');
        Route::post('/', [OrderController::class, 'store'])->name('store');
        Route::get('/{order}', [OrderController::class, 'show'])->name('show');
    });
});

Route Model Binding

Automatically inject model instances into your routes.

// Implicit Binding
Route::get('/users/{user}', function (User $user) {
    return $user->email;
});

// Custom Key Binding
Route::get('/posts/{post:slug}', function (Post $post) {
    return $post;
});

Dependency Injection & Service Container

The Service Container is a powerful tool for managing class dependencies.

Automatic Injection

Type-hint dependencies in controllers, jobs, or event listeners.

class UserController extends Controller
{
    public function __construct(
        protected UserRepository $users,
        protected PaymentService $payments
    ) {}
}

Binding Interfaces to Implementations

Use Service Providers to bind interfaces, allowing for easy swapping of implementations (Strategy Pattern).

// AppServiceProvider.php
public function register(): void
{
    $this->app->bind(PaymentGatewayInterface::class, StripePaymentGateway::class);
    
    // Singleton (shared instance)
    $this->app->singleton(LoggerService::class, function ($app) {
        return new LoggerService($app['config']['logging']);
    });
}

Middleware

Middleware provide a convenient mechanism for inspecting and filtering HTTP requests entering your application.

// bootstrap/app.php (Laravel 11+)
->withMiddleware(function (Middleware $middleware) {
    $middleware->append(EnsureTokenIsValid::class);
    
    $middleware->alias([
        'admin' => \App\Http\Middleware\EnsureUserIsAdmin::class,
    ]);
})