How can I check if request was a POST or GET request in Symfony2 or Symfony3

PhpSymfonyRequestHttp PostHttp Get

Php Problem Overview


I just wondered if there is a very easy way (best: a simple $this->container->isGet() I can call) to determine whether the request is a $_POST or a $_GET request.

According to the docs,

> A Request object holds information about the client request. This > information can be accessed via several public properties: > > - request: equivalent of $_POST; > - query: equivalent of $_GET ($request->query->get('name'));

But I won't be able to use if($request->request) or if($request->query) to check, because both are existing attributes in the Request class.

So I was wondering of Symfony offers something like the

$this->container->isGet();
// or isQuery() or isPost() or isRequest();

mentioned above?

Php Solutions


Solution 1 - Php

If you want to do it in controller,

$this->getRequest()->isMethod('GET');

or in your model (service), inject or pass the Request object to your model first, then do the same like the above.

Edit: for Symfony 3 use this code

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

Solution 2 - Php

Or this:

public function myAction(Request $request)
{
    if ($request->isMethod('POST')) {

    }
}

Solution 3 - Php

Or this:

use Symfony\Component\HttpFoundation\Request;

$request = Request::createFromGlobals();

    if ($request->getMethod() === 'POST' ) {
}

Solution 4 - Php

Since the answer suggested to use getRequest() which is now deprecated, You can do it by this:

$this->get('request')->getMethod() == 'POST'

Solution 5 - Php

You could do:

if($this->request->getRealMethod() == 'post') {
	// is post
}

if($this->request->getRealMethod() == 'get') {
	// is get
}

Just read a bit about request object on Symfony API page.

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
QuestionGottlieb NotschnabelView Question on Stackoverflow
Solution 1 - PhpNighonView Answer on Stackoverflow
Solution 2 - Phptimhc22View Answer on Stackoverflow
Solution 3 - PhpAzoelView Answer on Stackoverflow
Solution 4 - PhpMathenoView Answer on Stackoverflow
Solution 5 - PhpHelpNeederView Answer on Stackoverflow