php 检查请求是 GET 还是 POST

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21064582/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 03:47:56  来源:igfitidea点击:

Check if request is GET or POST

phppostgetlaravel-4

提问by JoeLoco

In my controller/action:

在我的控制器/动作中:

if(!empty($_POST))
{
    if(Auth::attempt(Input::get('data')))
    {
        return Redirect::intended();
    }
    else
    {
        Session::flash('error_message','');
    }
}

Is there a method in Laravelto check if the request is POSTor GET?

是否有一种方法Laravel可以检查请求是POST还是GET

采纳答案by Md Masud

I've solve my problem like below in laravel version: 7+

我已经在 laravel 版本中解决了我的问题,如下所示:7+

**In routes/web.php:**
Route::post('url', YourController@yourMethod);

**In app/Http/Controllers:**
public function yourMethod(Request $request) {
    switch ($request->method()) {
        case 'POST':
            // do anything in 'post request';
            break;

        case 'GET':
            // do anything in 'get request';
            break;

        default:
            // invalid request
            break;
    }
}

回答by Tom

According to Laravels docs, there's a Request method to check it, so you could just do:

根据Laravels docs,有一个 Request 方法来检查它,所以你可以这样做:

$method = Request::method();

or

或者

if (Request::isMethod('post'))
{
// 
}

回答by hubrik

The solutions above are outdated.

上面的解决方案已经过时了。

As per Laravel documentation:

根据Laravel 文档

$method = $request->method();

if ($request->isMethod('post')) {
    //
}

回答by giannis christofakis

Of course there is a method to find out the type of the request, Butinstead you should define a routethat handles POSTrequests, thus you don't need a conditional statement.

当然有一种方法可以找出请求的类型,但是您应该定义一个处理请求的路由POST,因此您不需要条件语句。

routes.php

路由文件

Route::post('url', YourController@yourPostMethod);

inside you controller/action

在你的控制器/动作里面

if(Auth::attempt(Input::get('data')))
{
   return Redirect::intended();
}
//You don't need else since you return.
Session::flash('error_message','');

The same goes for GETrequest.

这同样适用于GET请求。

Route::get('url', YourController@yourGetMethod);

回答by Pierre Emmanuel Lallemant

$_SERVER['REQUEST_METHOD']is used for that.

$_SERVER['REQUEST_METHOD']用于那个。

It returns one of the following:

它返回以下之一:

  • 'GET'
  • 'HEAD'
  • 'POST'
  • 'PUT'
  • '得到'
  • '头'
  • '邮政'
  • '放'

回答by Marcin Orlowski

Use Request::getMethod()to get method used for current request, but this should be rarely be needed as Laravel would call right method of your controller, depending on request type (i.e. getFoo()for GET and postFoo()for POST).

使用Request::getMethod()来获得用于当前请求的方法,但这应该是很少需要为Laravel会打电话给你的控制器的正确的方法,根据请求类型(即getFoo()对GET和postFoo()对POST)。