Check if request is GET or POST

后端 未结 6 1217
离开以前
离开以前 2021-02-04 23:37

In my controller/action:

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


        
相关标签:
6条回答
  • 2021-02-05 00:11

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

    It returns one of the following:

    • 'GET'
    • 'HEAD'
    • 'POST'
    • 'PUT'
    0 讨论(0)
  • 2021-02-05 00:16

    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;
        }
    }
    
    0 讨论(0)
  • 2021-02-05 00:18

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

    0 讨论(0)
  • 2021-02-05 00:20

    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'))
    {
    // 
    }
    
    0 讨论(0)
  • 2021-02-05 00:31

    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);
    
    0 讨论(0)
  • 2021-02-05 00:33

    The solutions above are outdated.

    As per Laravel documentation:

    $method = $request->method();
    
    if ($request->isMethod('post')) {
        //
    }
    
    0 讨论(0)
提交回复
热议问题