如何在Laravel中为相同的模式路由GET和POST?

问题描述 投票:32回答:9

有没有人知道Laravel 4将这两条线合二为一的方式?

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';
php laravel laravel-routing
9个回答
7
投票

您可以尝试以下方法:

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

然后在你的AuthController class实现这些方法:

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

它应该工作;)


56
投票

文件说......

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

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


32
投票

请参阅以下代码。

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

23
投票

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

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

这将匹配GETPOST HTTP动词。它也将匹配PUTPATCHDELETE


12
投票
Route::any('login', 'AuthController@login');

在控制器中:

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

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

1
投票

在laravel 5.1中,这可以通过Implicit Controllers实现。看看我从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()
    {
        //
    }
}

1
投票

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

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

https://laravel.com/docs/routing


0
投票

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

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

这应该够了吧。如果没有,那么泰勒将其从核心中移除;这意味着没有人使用它。

© www.soinside.com 2019 - 2024. All rights reserved.