2013-08-20 60 views
23

有没有人知道在Laravel 4中将这两条线合并为一个的任何方式?如何在Laravel中为相同模式路由GET和POST?

Route::get('login', '[email protected]'); 
Route::post('login', '[email protected]'); 

因此而不必写两个你只需要编写一个,因为他们都使用“相同”的方法,但也是URL仍然是site.com/login,而不是重定向到site.com/auth/login

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

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

回答

7

你可以尝试以下方法:

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

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

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

它应该工作;)

+3

来自未来的提示:[隐式控制器在Laravel 5.2中已弃用,将来会被删除](http://benjaminkohl.com/post/implicit-controller-routing-is-deprecated-in-laravel-5-2 )。 – jojonas

16

您可将所有HTTP动词使用的路线:

Route::any('login', '[email protected]'); 

这将匹配GETPOST HTTP动词。它也将匹配PUT,PATCH & DELETE

+0

如何检查动词是GET还是POST? – enchance

+0

你总是可以使用'$ _SERVER ['REQUEST_METHOD'] ==='POST',但我不会建议在一个动作中混合两个逻辑......带控制器的想法是**将逻辑**分开与Post-Redirect-Get模式一起使用。花2或3分钟阅读这个特定的线程:https://github.com/laravel/laravel/pull/1517。 –

+0

@enchance,你可以检查是'GET'或'POST'有: '如果(支持:: isMethod( '后'))'' {'' // ...'' }' – Sid

0

对,我回答使用我的手机,所以我没有测试过(如果我没有记错,它不在文档中)。这里去:

Route::match('(GET|POST)', 'login', 
    '[email protected]' 
); 

这应该做的伎俩。如果没有,那么泰勒将它从核心中移除;这意味着没有人使用它。

3
Route::match(array('GET', 'POST', 'PUT'), "/", array(
    'uses' => '[email protected]', 
    'as' => 'index' 
)); 
35

文档说...

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

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

+1

这个答案更精确。 –

+1

这应该是正确的答案。 – felipsmartins

+2

我很抱歉,这是如何得到这么多upvotes?是的,它解释了如何同时使用GET和POST,但没有说明如何根据请求类型调用不同的方法。 – lennard

6
Route::any('login', '[email protected]'); 

和控制器:

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

这是一个更好的答案。谢谢 – kikuyu1

1

在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() 
    { 
     // 
    } 
} 
相关问题