Check if request is GET or POST

和自甴很熟 提交于 2019-12-20 16:14:09

问题


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 Laravel to check if the request is POST or GET?


回答1:


Of course there is a method to find out the type of the request, But instead you should define a route that handles POST requests, thus you don't need a conditional statement.

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 GET request.

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



回答2:


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

$method = Request::method();

or

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



回答3:


The solutions above are outdated.

As per Laravel documentation:

$method = $request->method();

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



回答4:


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).




回答5:


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

It returns one of the following:

  • 'GET'
  • 'HEAD'
  • 'POST'
  • 'PUT'


来源:https://stackoverflow.com/questions/21064582/check-if-request-is-get-or-post

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!