Question

I am trying to retrieve parameters from a PUT request using the Slim framework. When parsing parameters form a POST body, I can simply use $request->post('param') to retrieve the value in param. However, when I use $request->put('param'), I always receive null.

My PUT body is formed like this: param=value&otherparam=othervalue&foo=bar...

P.S.: I have already looked at this question, but the answer did not use the put()-Method.

Was it helpful?

Solution

You're getting null back from $request->put('param') because you're trying to call that on a POST route. You'll need to create a separate PUT route (or use map and via) before you can get the PUT param.

Additionally, I don't recommend adding the HTTP verb to the route. That leads to some really confusing architecture.

Adding an additional route:

$app->post('/api/something/:id', function () {});
$app->put('/api/something/:id', function () {});

Using Custom HTTP methods (map and via)

$app->map('/api/something/:id', function () {})->via('POST', 'PUT');

Please see the PUT routing documentation, and pay special attention to the Method Override section.

UPDATE: Working Example

Here is an example PUT request I whipped up:

$app->put('/test/:id', function ($id) use ($app) {
    $name = $app->request->put('name');
    echo sprintf('PUT request for resource id %d, name "%s"', (int) $id, $name);
});

I'm calling it with cURL from the command line like so:

curl -X PUT -d name=arthur http://slim-tutorial.dev/test/2

The result:

PUT request for resource id 2, name "arthur"%

If you've got a working Slim application and the above doesn't work for you, likely the problem is somewhere outside of Slim, perhaps in how you're testing or a typo in your route or test parameters.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top