如何在 Laravel 中路由 GET 和 POST 以获得相同的模式


How to route GET and POST for same pattern in Laravel?

>有谁知道在 Laravel 4 中有什么方法可以将这 2 行合二为一?

Route::get('login', 'AuthController@getLogin');
Route::post('login', 'AuthController@postLogin');
因此,您不必同时编写两者,您只需

编写一个,因为它们都使用"相同"的方法,而且 URL 保持site.com/login而不是重定向到 site.com/auth/login

我很好奇,因为我记得 CI 有类似的东西,其中 URL 保持不变并且控制器从未显示:

$route['(method1|method2)'] = 'controller/$1';

文档说...

Route::match(array('GET', 'POST'), '/', function()
{
    return 'Hello World';
});

来源: http://laravel.com/docs/routing

请参阅下面的代码。

Route::match(array('GET','POST'),'login', 'AuthController@login');

您可以使用以下方法组合路由的所有 HTTP 谓词:

Route::any('login', 'AuthController@login');

这将匹配 GETPOST HTTP 谓词。它也可以匹配PUTPATCHDELETE

Route::any('login', 'AuthController@login');

在控制器中:

if (Request::isMethod('post'))
{
// ... this is POST method
}
if (Request::isMethod('get'))
{
// ... this is GET method
}
...

您可以尝试以下操作:

Route::controller('login','AuthController');

然后在您的AuthController class实现以下方法:

public function getIndex();
public function postIndex();

它应该;)工作

根据最新的文档,它应该是

Route::match(['get', 'post'], '/', function () {
    //
});

https://laravel.com/docs/routing

Route::match(array('GET', 'POST', 'PUT'), "/", array(
    'uses' => 'Controller@index',
    'as' => 'index'
));

在路由中

Route::match(array('GET','POST'),'/login', 'AuthController@getLogin');

在控制器中

public function login(Request $request){
    $input = $request->all();
    if($input){
     //Do with your post parameters
    }
    return view('login');
}

在 laravel 5.1 中,这可以通过隐式控制器来实现。看看我从Laravel文档中发现了什么

Route::controller('users', 'UserController');

接下来,只需向控制器添加方法。方法名称应以它们响应的 HTTP 谓词开头,后跟 URI 的标题大小写版本:

<?php
namespace App'Http'Controllers;
class UserController extends Controller
{
    /**
     * Responds to requests to GET /users
     */
    public function getIndex()
    {
        //
    }
    /**
     * Responds to requests to GET /users/show/1
     */
    public function getShow($id)
    {
        //
    }
    /**
     * Responds to requests to GET /users/admin-profile
     */
    public function getAdminProfile()
    {
        //
    }
    /**
     * Responds to requests to POST /users/profile
     */
    public function postProfile()
    {
        //
    }
}

使用匹配来处理这两种方法

Route::match(['GET','POST'], 'users', UserController@store);

是的,我正在使用我的手机回答,所以我还没有测试过这个(如果我没记错的话,它也不在文档中(。这里是:

Route::match('(GET|POST)', 'login',
    'AuthController@login'
);

这应该可以解决问题。如果没有,那么泰勒将其从核心中移除;这意味着没有人使用它。