404 URLs does not pass through web Middlewares in Laravel 11, php8.2 and TwillCMS. How to solve this issue?

Updated: Jan 30, 2025

404 URLs does not pass through web Middlewares in Laravel 11, php8.2 and TwillCMS. How to solve this issue?

To answer your question, let me first explain what a 404 URL is and how it relates to web middlewares in Laravel, along with the versions you mentioned (Laravel 11, PHP 8.2, and TwillCMS).

A 404 error is an HTTP status code that indicates that the requested URL cannot be found on the server. When a user tries to access a page that does not exist, Laravel will return a 404 error by default.

Web middlewares in Laravel are essentially filters that are applied to incoming requests before they reach the route handler. Middlewares can be used for various purposes, such as authentication, rate limiting, and caching.

However, by default, Laravel does not apply web middlewares to 404 errors. This is because 404 errors are considered to be an error response, and applying middlewares to error responses could potentially introduce security vulnerabilities or other unintended consequences.

Now, let's talk about the specific issue you mentioned, which is related to Laravel 11, PHP 8.2, and TwillCMS. TwillCMS is a popular Laravel-based CMS that allows users to create and manage content without requiring extensive PHP knowledge.

If you're experiencing an issue where 404 URLs are not passing through web middlewares in Laravel 11 with PHP 8.2 and TwillCMS, there are a few potential solutions you can try:

  1. Use a global error handler middleware: Instead of applying middlewares to specific routes, you can define a global error handler middleware that will be applied to all error responses, including 404 errors. To do this, create a new middleware and define the terminate method, which will be called when an error occurs. In this method, you can perform any actions you need to take when an error occurs, such as logging the error or sending a response to the user. Here's an example of how to create a global error handler middleware in Laravel:
namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Response;

class ErrorHandler
{
    public function handle($request, Closure $next, $exception = null)
    {
        if ($exception instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException) {
            // Handle 404 errors here
            return response()->view('errors.404', [], 404);
        }

        return $next($request);
    }

    public function terminate($request, $response)
    {
        if ($exception = $e = $request->getAttribute('exception')) {
            // Log the error here
            // ...

            // Return a custom response to the user
            return response()->view('errors.500', [], 500);
        }
    }
}

In this example, the middleware checks if the exception is an instance of NotFoundHttpException, which is the exception that is thrown when a requested route or controller method is not found. If it is, the middleware returns a custom 404 response.

  1. Use a route model binding exception middleware: Another approach is to define a middleware that handles exception thrown when a route model binding fails. This middleware will be triggered when Laravel is unable to find the model for a given route. To create this middleware, you can use the modelBindingException event and listen for it in the terminate method. Here's an example of how to create a route model binding exception middleware in Laravel:
namespace App\Http\Middleware;

use Closure;
use Illuminate\Routing\Route;
use Illuminate\Support\Facades\App;

class ModelBindingExceptionMiddleware
{
    public function handle($request, Closure $next, $exception = null)
    {
        if ($exception instanceof \Illuminate\Routing\Exceptions\ModelBindingException) {
            // Handle model binding exceptions here
            $model = App::make(lcfirst(explode(':', $exception->getModel()))[0]);
            $message = 'The ' . str_singular(class_basename($model)) . ' was not found.';

            return response()->view('errors.404', ['message' => $message], 404);
        }

        return $next($request);
    }

    public function terminate($request, $response)
    {
        // ...
    }
}

In this example, the middleware listens for the modelBindingException event and checks if the exception is an instance of ModelBindingException. If it is, the middleware creates an instance of the model using its name, and returns a custom 404 response with an error message.

  1. Use a custom error view: Finally, you can define a custom error view for 404 errors and return it directly from the render method of the App\Exceptions\Handler class. This approach does not involve creating a middleware, but it can still help you display a custom error message to the user when a 404 error occurs. Here's an example of how to define a custom error view in Laravel:
namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Routing\RoutingException;
use Illuminate\View\View;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed to the session on validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'current_password', 'password', 'password_confirmation',
    ];

    /**
     * Report or log an exception.
     *
     * @param  \Throwable  $e
     * @return void
     */
    public function report(Throwable $e)
    {
        parent::report($e);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Throwable  $exception
     * @return \Illuminate\Http\Response|\Illuminate\View\View
     */
    public function render($request, Throwable $exception)
    {
        if ($exception instanceof RoutingException) {
            return view('errors.404');
        }

        return parent::render($request, $exception);
    }
}

In this example, the render method checks if the exception is an instance of RoutingException, which is the exception that is thrown when a requested route is not found. If it is, the method returns a custom 404 view instead of the default 404 response.

I hope this explanation and the provided solutions help you solve the issue you're experiencing with 404 URLs not passing through web middlewares in Laravel 11, PHP 8.2, and TwillCMS. Let me know if you have any questions or if there's anything else I can help you with.