Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Kjell's avatar
Level 4

Perform action after at the end of each request lifecycle

After each api call i would like to have an action performed.

Like a middleware, but after the controller method has been executed.

Where is the best way to add such logic?

0 likes
17 replies
Sinnbeck's avatar

Why not just dispatch an event in the controller method?

Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

Try adding a middleware with this handle method

public function handle($request, Closure $next)
{
    $response = $next($request);
    // do stuff 
    return $response;
}
1 like
Kjell's avatar
Level 4

This is my middleware:


namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class Language
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        if (Auth::check()) {
            App::setLocale(Auth::user()->language->key);
        }

        echo " - mw before - ";

        $response = $next($request);

        // Perform action
        echo " - mw after - ";

        // return $next($request);
        return $response;
    }
}

controller function:

    public function index(Request $request)
    {
        return ' - squad controller index - ';
    }

Which gives in the api response:

  • mw before - - mw after - - squad controller index -

And i would like to have:

  • mw before - - squad controller index - - mw after -
Kjell's avatar
Level 4

@Sinnbeck

Illuminate\Http\Response {#1858
  +headers: Symfony\Component\HttpFoundation\ResponseHeaderBag {#1880
    #computedCacheControl: array:2 [
      "no-cache" => true
      "private" => true
    ]
    #cookies: []
    #headerNames: array:5 [
      "content-type" => "Content-Type"
      "cache-control" => "Cache-Control"
      "date" => "Date"
      "x-ratelimit-limit" => "X-RateLimit-Limit"
      "x-ratelimit-remaining" => "X-RateLimit-Remaining"
    ]
    #headers: array:5 [
      "content-type" => array:1 [
        0 => "text/html; charset=UTF-8"
      ]
      "cache-control" => array:1 [
        0 => "no-cache, private"
      ]
      "date" => array:1 [
        0 => "Tue, 11 Jan 2022 08:31:03 GMT"
      ]
      "x-ratelimit-limit" => array:1 [
        0 => 60
      ]
      "x-ratelimit-remaining" => array:1 [
        0 => 59
      ]
    ]
    #cacheControl: []
  }
  #content: " - squad controller index - "
  #version: "1.1"
  #statusCode: 200
  #statusText: "OK"
  #charset: null
  +original: " - squad controller index - "
  +exception: null
}

The middleware with the dd:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class Language
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        if (Auth::check()) {
            App::setLocale(Auth::user()->language->key);
        }

        echo " - mw before - ";

        $response = $next($request);

        dd($response);
        // Perform action
        echo " - mw after - ";

        // return $next($request);
        return $response;
    }
}

Kjell's avatar
Level 4

@furqanDev Thanks! But, it should happen before the reply is sent to the browser.

martinbean's avatar

it should happen before the reply is sent to the browser.

@Kjell Why? What’s the difference? A controller returns a response. That response is sent to the user.

Maybe explain what you’re trying to do; not how you’re trying to do it.

2 likes
Snapey's avatar

you cannot go by the order of the echo statements. the response is sent last. your echoes are output immediately

1 like
tykus's avatar

I suppose that the actual Response is not some random - squad controller index - string, and the middleware is to append something (useful) to the JSON???

What you actually need to do in the Middleware to modify the Response's content.

$response = $next($request);
$payload = $response->getOriginalContent();
// do something to modify the payload
$content = $payload //... some operation(s)

$response->setContent($content);
return $response;

It is difficult to reason about your use case however, so I don't know if this is what you're after - echo doesn't make sense in any context never mind an API...

Kjell's avatar
Level 4

Thanks @sinnbeck for giving the answer: https://laracasts.com/discuss/channels/requests/perform-action-after-at-the-end-of-each-request-lifecycle?page=1&replyId=761785

But then I made a mistake with returning a string in the controller, which would always be at the end.

So the reply of @snapey (https://laracasts.com/discuss/channels/requests/perform-action-after-at-the-end-of-each-request-lifecycle?page=1&replyId=762015) pushed me in the right direction.

So to be sure: I did some echos in stead of return in the controller.

middleware:

<?php

namespace App\Http\Middleware;

use App\Models\PoolType;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class Language
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        echo " - mw before - ";

        $response = $next($request);

        echo " - mw after - ";

        return $response;
    }
}

Controller:

class SquadController extends Controller
{

    public function index(Request $request)
    {

        echo " - SquadController index - ";
        return null;
    }
}

Output:

 - mw before -  - SquadController index -  - mw after - 

Thanks everyone!

Kjell's avatar
Level 4

@tykus Hahaha! This is a proof of concept. Of course this is not the end product.

This thread was just about the sequence of statements.

tykus's avatar

@Kjell but utterly useless in real terms - echoing strings will not be a feature of your API I hope

Kjell's avatar
Level 4

@tykus Of course not.

On the place of each echo is a lot of business logic. Which was not important to solve this issue.

martinbean's avatar

On the place of each echo is a lot of business logic. Which was not important to solve this issue.

@Kjell It kinda was as then we could have guided you to an actual solution. But instead you just came asking about you’re already-conceived solution instead of the actual problem you were trying to solve. Class XY Problem.

Please or to participate in this conversation.