Bird
Raised Fist0
Laravelframework~10 mins

Terminable middleware in Laravel - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Terminable middleware
Request enters middleware
↓
Handle method runs
↓
Pass request to next middleware or app
↓
Response generated and sent back
↓
Terminable middleware's terminate method runs
↓
Cleanup or logging after response
↓
End
The middleware first handles the request, then after the response is sent, the terminate method runs for cleanup or logging.
Execution Sample
Laravel
class LogAfterResponse implements TerminableMiddleware {
  public function handle($request, Closure $next) {
    return $next($request);
  }
  public function terminate($request, $response) {
    // Log after response sent
  }
}
Middleware that passes the request through and logs after the response is sent.
Execution Table
StepActionRequest StateResponse StateMiddleware MethodEffect
1Request enters middlewareReceivedNonehandleMiddleware starts processing
2handle calls next middleware/appPassed alongNonehandleRequest forwarded
3Response generated by appProcessedGeneratedhandleResponse ready to send
4Response sent to clientProcessedSenthandleClient receives response
5terminate method runsProcessedSentterminateLogs or cleanup after response
6Middleware finishesProcessedSentterminateMiddleware work complete
💡 terminate runs after response sent, then middleware completes
Variable Tracker
VariableStartAfter handleAfter responseAfter terminateFinal
requestIncoming HTTP requestPassed to nextProcessed by appAvailable for terminateNo change
responseNoneNoneCreated by appSent to clientNo change
Key Moments - 2 Insights
Why does the terminate method run after the response is sent?
Because terminate is designed to run after the response is sent to allow tasks like logging or cleanup without delaying the user.
Can the terminate method modify the response sent to the client?
No, terminate runs after the response is sent, so it cannot change what the client receives, only perform post-response actions.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, at which step is the response sent to the client?
AStep 3
BStep 5
CStep 4
DStep 2
💡 Hint
Check the 'Effect' column for when the client receives the response.
According to variable_tracker, what is the state of the request during the terminate method?
AIncoming HTTP request
BAvailable for terminate
CPassed to next
DProcessed by app
💡 Hint
Look at the 'After terminate' column for the request variable.
If the terminate method tried to modify the response, what would happen?
AThe modification would be ignored because response is already sent
BThe client would see the modified response
CThe response would be delayed until terminate finishes
DAn error would occur
💡 Hint
Refer to key_moments about when terminate runs relative to response sending.
Concept Snapshot
Terminable middleware in Laravel has two parts:
- handle method: processes request and passes it on
- terminate method: runs after response sent for cleanup or logging
Terminate cannot change the response sent to client.
Useful for tasks that should not delay user experience.
Full Transcript
Terminable middleware in Laravel works by first handling the incoming request in the handle method. This method passes the request to the next middleware or the application, which generates a response. After the response is sent to the client, the terminate method runs. This method is useful for tasks like logging or cleanup that should happen after the user receives the response. The terminate method cannot modify the response because it runs after sending. The execution flow starts with the request entering middleware, handle passing it on, response generation, response sending, then terminate running, and finally middleware finishing. Variables like request and response change state accordingly but remain accessible in terminate for post-response actions.

Practice

(1/5)
1. What is the main purpose of terminable middleware in Laravel?
easy
A. To validate user input before processing
B. To modify the HTTP request before it reaches the controller
C. To handle database migrations automatically
D. To run code after the HTTP response has been sent to the user

Solution

  1. Step 1: Understand middleware timing

    Terminable middleware runs after the response is sent, unlike regular middleware that runs before.
  2. Step 2: Identify terminable middleware purpose

    It is used for tasks like logging or cleanup after response delivery.
  3. Final Answer:

    To run code after the HTTP response has been sent to the user -> Option D
  4. Quick Check:

    Terminable middleware = post-response code [OK]
Hint: Terminable middleware runs after response is sent [OK]
Common Mistakes:
  • Confusing terminable middleware with regular middleware
  • Thinking it runs before the controller
  • Assuming it handles request validation
2. Which method must be implemented in a Laravel terminable middleware class?
easy
A. handle
B. process
C. terminate
D. finish

Solution

  1. Step 1: Recall terminable middleware interface

    Terminable middleware requires a terminate method to run code after response.
  2. Step 2: Differentiate from handle method

    handle runs before response, terminate runs after.
  3. Final Answer:

    terminate -> Option C
  4. Quick Check:

    Post-response method = terminate [OK]
Hint: Terminate method runs after response in terminable middleware [OK]
Common Mistakes:
  • Using handle instead of terminate for post-response code
  • Assuming process or finish are valid methods
  • Not implementing terminate method at all
3. Given this terminable middleware code, what will be logged after the response is sent?
class LogAfterResponse {
    public function handle($request, Closure $next) {
        return $next($request);
    }
    public function terminate($request, $response) {
        Log::info('Response sent with status: ' . $response->status());
    }
}
medium
A. Logs the request URL before sending the response
B. Logs the response status code after sending the response
C. Throws an error because terminate method is missing parameters
D. Does nothing because terminate is not called automatically

Solution

  1. Step 1: Analyze handle method

    The handle method passes the request to next middleware/controller without changes.
  2. Step 2: Analyze terminate method

    After response is sent, terminate logs the response status code using Log::info.
  3. Final Answer:

    Logs the response status code after sending the response -> Option B
  4. Quick Check:

    terminate logs status post-response [OK]
Hint: Terminate runs after response, so logs status then [OK]
Common Mistakes:
  • Thinking terminate runs before response
  • Assuming terminate is not called automatically
  • Confusing request and response parameters
4. Identify the error in this terminable middleware code:
class CleanupMiddleware {
    public function handle($request, Closure $next) {
        return $next($request);
    }
    public function terminate() {
        // cleanup code here
    }
}
medium
A. terminate method must accept $request and $response parameters
B. handle method must return a string, not a response
C. terminate method should be named handleTerminate
D. handle method must not call $next

Solution

  1. Step 1: Check terminate method signature

    Terminable middleware's terminate method must accept both $request and $response parameters.
  2. Step 2: Identify missing parameters

    The code's terminate method has no parameters, which will cause errors.
  3. Final Answer:

    terminate method must accept $request and $response parameters -> Option A
  4. Quick Check:

    terminate signature requires request and response [OK]
Hint: Terminate method needs both request and response parameters [OK]
Common Mistakes:
  • Omitting parameters in terminate method
  • Renaming terminate method incorrectly
  • Misunderstanding handle method return type
5. You want to log the total time taken to process a request including after the response is sent. How would you implement this using terminable middleware?
class RequestTimer {
    protected $startTime;

    public function handle($request, Closure $next) {
        $this->startTime = microtime(true);
        return $next($request);
    }

    public function terminate($request, $response) {
        // What code should go here?
    }
}
hard
A. $duration = microtime(true) - $this->startTime; \Log::info('Request took ' . $duration . ' seconds');
B. $duration = microtime(true) + $this->startTime; \Log::info('Request took ' . $duration . ' seconds');
C. return $this->startTime; // terminate must return a value
D. Call $this->handle($request, $next) again inside terminate

Solution

  1. Step 1: Calculate duration in terminate method

    Use current time minus stored start time to get total duration.
  2. Step 2: Log the duration

    Use Log::info to record the time taken after response is sent.
  3. Final Answer:

    $duration = microtime(true) - $this->startTime; \Log::info('Request took ' . $duration . ' seconds'); -> Option A
  4. Quick Check:

    Duration = now - startTime, then log [OK]
Hint: Subtract start time from current time in terminate to get duration [OK]
Common Mistakes:
  • Adding times instead of subtracting
  • Returning values from terminate method
  • Calling handle method inside terminate
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard