phproutesilluminate

For 404 on illuminate/routing outside framework


$dispatcher = new Illuminate\Events\Dispatcher;
$router = new Illuminate\Routing\Router($dispatcher);

$router->get( '/', [ HomeController::class, 'index' ] );

$request = Illuminate\Http\Request::createFromGlobals();
$response = $router->dispatch($request);
$response->send();

When I want to go /home, try to get the 404 page that I cannot get the 404 error page, and see Fatal error: Uncaught Symfony\Component\HttpKernel\Exception\NotFoundHttpException only

Also, I try to AbstractRouteCollection.php change the handleMatchedRoute method from

throw new NotFoundHttpException;

to

require_once( ROOT . DS . "responses" . DS . "error" . DS . "404.php" );

I can show the 404 page but get error Fatal error: Uncaught Error: Call to a member function setContainer() on null

I have no idea what I can do.

composer.json

{
    "require": {
        "vlucas/phpdotenv": "^5.3",
        "google/apiclient": "^2.10",
        "facebook/graph-sdk": "5.7.0",
        "illuminate/database": "^8.62",
        "illuminate/routing": "^8.64",
        "illuminate/events": "^8.64"
    },
    "autoload": {
        "psr-4": {
            "App\\": "app/",
            "Config\\": "config/"
        }
    }
}

Solution

  • A possible solution to this problem is to add the following lines after having all your routes declared to avoid affecting the operation of the previous routes:

    $router->any('{path?}', function () {
        // Return your view or response
        return json_encode(['status' => 'fail', 'message' => '404 error']);
    })->where('path', '(.*)');
    

    We are saying that any path or url will be answered with what we say, for that reason it must be below the necessary routes in your project, if it is first it will affect the other routes and they will not work correctly.