Laravel路由url在app() - > handle()函数后更改

I'm accessing an api in my own project, but now I'm having problem with the route function, after dispatching the request with app()->handle($req), route function generate a different url

   $req = Request::create('/api/auth/login', 'POST', [
        "user" => $request->user,
        "password" => $request->password,
    ]);

    $redirect = route('home'); // http://127.0.0.1:8000/home

    $res = app()->handle($req);

    $redirect = route('home'); // http://localhost/home

What did I miss?

Request::create() is a method inherited from Symfony's HTTP Request class. When called, if you do not pass in any $_SERVER details, it will use reasonable defaults.

The UrlGenerator Laravel class uses the current Request to determine the fully-qualified domain name when calling functions such as route(). Since you did not tell the Request what the current domain is, it is reverting to localhost.

If you're in an environment where $_SERVER is populated with the proper information, you can pass it to the proper parameter:

Request::create(
    '/api/auth/login',
    'POST',
    [
        'user' => $request->user,
        'password' => $request->password,
    ],
    [], // cookies
    [], // files
    $_SERVER
);

Other potential solutions that may fit well:

  • Use Request::createFromGlobals() to populate a request with PHP's superglobals such as $_POST, $_SERVER, etc., then modify the parts that you want to change.
  • If the $request variable already holds a Laravel Request instance, you can call $request->duplicate(). And again, modify as needed.