Check if request is GET or POST

PhpPostGetLaravel 4

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

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'))
{
// 
}

Solution 2 - Php

The solutions above are outdated.

As per Laravel documentation:

$method = $request->method();

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

Solution 3 - Php

I've solve my problem like below in laravel version: 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;
    }
}

Solution 4 - Php

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

Solution 5 - Php

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

It returns one of the following:

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

Solution 6 - Php

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJoeLocoView Question on Stackoverflow
Solution 1 - PhpTomView Answer on Stackoverflow
Solution 2 - PhphubrikView Answer on Stackoverflow
Solution 3 - Phpuser9916289View Answer on Stackoverflow
Solution 4 - Phpgiannis christofakisView Answer on Stackoverflow
Solution 5 - PhpPierre Emmanuel LallemantView Answer on Stackoverflow
Solution 6 - PhpMarcin OrlowskiView Answer on Stackoverflow