How do you use route parameters in Slim Framework?

How do you use route parameters in Slim Framework?

To use route parameters in the Slim Framework, follow these steps:

Steps to Use Route Parameters in Slim Framework

  1. Install Slim Framework: If you haven’t already, install Slim via Composer.

Example

composer require slim/slim "^4.0"
  1. Set Up Your Slim Application:
Create a new PHP file (e.g., index.php) and set up your Slim application.

Example

<?php
<?php
require 'vendor/autoload.php';

use Slim\Factory\AppFactory;

// Create Slim App
$app = AppFactory::create();
?>
  1. Define a Route with Parameters:
Create a route that includes parameters in the URL. Parameters are defined using curly braces {}.

Example

<?php
// Define a route with a parameter
$app->get('/user/{id}', function ($request, $response, $args) {
    $userId = $args['id']; // Access the route parameter
    $response->getBody()->write("User ID: " . $userId);
    return $response;
});
?>
  1. Add More Parameters (Optional):
You can also add multiple parameters to a route.

Example

<?php
// Define a route with multiple parameters
$app->get('/user/{id}/{name}', function ($request, $response, $args) {
    $userId = $args['id'];
    $userName = $args['name'];
    $response->getBody()->write("User ID: " . $userId . ", Name: " . $userName);
    return $response;
});
?>
  1. Run the Application:
Start your Slim application by running the PHP built-in server or any other server.

Example

php -S localhost:8080 index.php
  1. Access the Route: Open your web browser and navigate to http://localhost:8080/user/1 or http://localhost:8080/user/1/John to see the output of the route with parameters.

Example Output

  • For http://localhost:8080/user/1, the output will be:

Example

User ID: 1
  1. For http://localhost:8080/user/1/John, the output will be:

Example

User ID: 1, Name: John

Related Questions & Topics