How can you create a route that handles multiple HTTP methods?

How can you create a route that handles multiple HTTP methods?

In Slim Framework, you can create a route that handles multiple HTTP methods (e.g., GET, POST, PUT, DELETE) by using the map() method, which allows you to specify multiple methods for a single route.

Example:

Example

<?php
$app->map(['GET', 'POST'], '/example', function ($request, $response) {
    if ($request->getMethod() == 'GET') {
        // Handle GET request
        return $response->write('GET request');
    } elseif ($request->getMethod() == 'POST') {
        // Handle POST request
        return $response->write('POST request');
    }
});
?>

Breakdown:

  • map() accepts an array of HTTP methods (e.g., ['GET', 'POST']) as the first argument.
  • The second argument is the route (/example in this case).
  • Inside the route handler, you can use $request->getMethod() to check the request method and execute different logic based on that.

Alternative (using any() method):

If you want to handle any HTTP method, you can use the any() method:

Example

<?php
$app->any('/example', function ($request, $response) {
    return $response->write('This handles any HTTP method');
});
?>

This way, the route will accept any HTTP method and handle the request accordingly.

Related Questions & Topics