Laravel route url changing after app()->handle() function

ぃ、小莉子 提交于 2019-12-02 18:33:08

问题


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?


回答1:


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.


来源:https://stackoverflow.com/questions/50705869/laravel-route-url-changing-after-app-handle-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!