Check if request is GET or POST

2019-03-17 05:13发布

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?

5条回答
Lonely孤独者°
2楼-- · 2019-03-17 05:45

The solutions above are outdated.

As per Laravel documentation:

$method = $request->method();

if ($request->isMethod('post')) {
    //
}
查看更多
Ridiculous、
3楼-- · 2019-03-17 05:50

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'))
{
// 
}
查看更多
forever°为你锁心
4楼-- · 2019-03-17 05:50

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

It returns one of the following:

  • 'GET'
  • 'HEAD'
  • 'POST'
  • 'PUT'
查看更多
SAY GOODBYE
5楼-- · 2019-03-17 06:03

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

查看更多
Summer. ? 凉城
6楼-- · 2019-03-17 06:12

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);
查看更多
登录 后发表回答