php - How to properly overwrite `IlluminateRoutingRouter::toResponse` in order to send HTTP status code 204 for empty responses?

one text

Solution:

Found a solution which is much easier than overwriting the Router. I can use a middleware which modifies the response after the controller method has run, but before the response is sent to the client: a so-called response middleware (see Laravel Documentation "Middleware $ Responses").

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Ensures that responses with empty content return status code 204.
 *
 * This fixes a bug in Laravel.
 */
class FixStatusCode {
  /**
   * Handle an incoming request.
   *
   * @param Request  $request
   * @param \Closure $next
   *
   * @return Response
   *
   * @throws \InvalidArgumentException
   */
  public function handle(Request $request, Closure $next): Response {
    /** @var Response $response */
    $response = $next($request);
    
    if (empty($response->getContent())) {
      $response->setStatusCode(Response::HTTP_NO_CONTENT);
    }
    
    return $response;
  }
}

Then, I have to register this middleware like any other middleware in App\Http\Kernel::$middleware.

Source