Back to Engineering Notes
Laravel ConceptsEngineering Note

3. Middleware

I use Middleware to control request flow and handle shared logic in a clean and reusable way.

🧠 Middleware (Laravel)

I use Middleware to control request flow and handle shared logic in a clean and reusable way.


🎯 Simple Idea

Middleware works like a pipeline or gatekeeper:

👉 Client → Middleware → Controller → Middleware → Response


🔄 How It Works

Request enters the application
Passes through middleware (before controller)
Middleware can:
allow the request
block it (e.g., unauthorized)
modify it
Controller executes
Response is returned
Response passes back through middleware

🔁 Visualization

plain text
Request →
  Middleware A →
    Middleware B →
      Controller →
    Middleware B →
  Middleware A →
Response

👉 Middleware can run on both:

before controller → handle request
after controller → handle response

🧩 Types of Middleware I Use

Global Middleware

runs for every request

👉 used for logging, security, request normalization


Route Middleware

applied to specific routes

👉 used for authentication and authorization


Group Middleware

applied to a group of routes

👉 used for APIs, admin modules, shared rules


🧩 Laravel Example

Create Middleware

plain text
php artisanmake:middleware CheckRole

Middleware Logic

plain text
public function handle($request, Closure $next)
{
    if ($request->user()->role !== 'admin') {
        return response()->json(['message' => 'Unauthorized'], 403);
    }

    return $next($request);
}

👉 $next($request) passes control to the next step


Register Middleware

In app/Http/Kernel.php:

plain text
protected $routeMiddleware = [
    'role' => \App\Http\Middleware\CheckRole::class,
];

Apply Middleware

plain text
Route::get('/admin', function () {
    return 'Admin Page';
})->middleware('role');

🧠 Why I Use This

avoids repeating logic in controllers
keeps controllers clean and focused
centralizes cross-cutting concerns
makes request flow predictable

⚖️ Tradeoff Awareness

too many middleware → harder to trace flow
putting business logic inside middleware → bad practice

📌 Practical Rule

> middleware = shared request/response handling, not business logic


💬 Summary

Middleware helps me:

control request flow
apply consistent rules
keep code structured and maintainable

👉 builds systems that are clean, predictable, and scalable 👍