Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 401
Gottlieb Notschnabel Avatar asked Apr 04 '14 02:04

Gottlieb Notschnabel


2 Answers

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
}
like image 178
Nighon Avatar answered Nov 12 '22 11:11

Nighon


Or this:

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

    }
}
like image 46
timhc22 Avatar answered Nov 12 '22 12:11

timhc22