首页 > 解决方案 > Laravel 默认 make:auth "login" 路由命名

问题描述

当我学习 Laravel (5.6) 内置身份验证使用make:auth和挖掘生成的路由时,我注意到了 Laravel 的路由命名。

首先,我发现这些是使用时注册的路由make:auth

// Authentication Routes...
        $this->get('login', 'Auth\LoginController@showLoginForm')->name('login');
        $this->post('login', 'Auth\LoginController@login');
        $this->post('logout', 'Auth\LoginController@logout')->name('logout');

        // Registration Routes...
        $this->get('register', 'Auth\RegisterController@showRegistrationForm')->name('register');
        $this->post('register', 'Auth\RegisterController@register');

        // Password Reset Routes...
        $this->get('password/reset', 'Auth\ForgotPasswordController@showLinkRequestForm')->name('password.request');
        $this->post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail')->name('password.email');
        $this->get('password/reset/{token}', 'Auth\ResetPasswordController@showResetForm')->name('password.reset');
        $this->post('password/reset', 'Auth\ResetPasswordController@reset');

第一个,GET名为 的路由login,将调用Auth\LoginController@showLoginForm渲染auth.login视图。

第二个路由,一个无名POST路由,将调用Auth\LoginController@login从表单中检索提交的数据并对用户进行身份验证。

但是当我查看生成auth.login视图的表单时,它的操作是POST对 route 的请求login

<form method="POST" action="{{ route('login') }}" aria-label="{{ __('Login') }}">

AFAIK,此表单将调用Auth\LoginController@showLoginForm而不是 Auth\LoginController@login基于表单上定义的路由名称action(即login)。但是当使用表单时,它会正确调用Auth\LoginController@login. 这怎么可能?

标签: phplaravel

解决方案


route帮助程序生成 URL 。这 2 条路由的 URI(路径)与刚刚为不同 HTTP 方法注册的完全相同的 URI/路径。

因此,当您使用该方法时,您将获得一个指向http://yoursite/login. 这里没有 HTTP 方法的含义。这取决于提出的请求来决定它使用什么方法。URL 无论如何都是 URL。

请求进来并匹配一个 URI,请求也将有一个 HTTP 方法。如果它有 HTTP 方法 GET 它会命中get路由,如果它有 HTTP 方法 POST 它会命中post定义的路由。

URI 与控制器方法不匹配。在这种情况下,URI 和 HTTP 方法共同决定。


推荐阅读