How to check if route has placeholder

I’m using Slim 4, php-di, and eloquent orm currently. So

If I have route like this

$app->get('users/{user}', [UserController::class, 'show'])->setName('show.user');

$app->get('posts/{post}', [PostController::class, 'show'])->setName('show.post');

And some mapping like this

$routeToModel = [
  'user' => User::class,
  'post' => Post::class
];

How to check if current route has placeholder and match one of item in $routeToModel. So I can retrieve the data within controller/middleware

To retrieve the route parameter values within a controller, you can use the 3. argument (array $args).

Pseudo example:

public function show(Request $request, Response $response, array $args)
{
    $name = (string)$args['user'];

    $response->getBody()->write("Hello, $user");

    return $response;
}

To retrieve the route parameter values within a middleware (PSR-15), you may use the RouteContext class.

use Slim\Routing\RouteContext;
// ...

$routeArguments = RouteContext::fromRequest($request)
    ->getRoute()
    ->getArguments();

I’ll try this in middleware then

use Slim\Routing\RouteContext;
// ...

$routeArguments = RouteContext::fromRequest($request)
    ->getRoute()
    ->getArguments();

foreach ($routeArguments as $key => $argument) {
  if (!is_null($model = $routeToModel[$key])) {
    $request = $request->withAttribute($key, $model::find($argument));
  }
}

and in controller

use App\Models\User;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;

public function show(Request $request, Response $response)
{
  return $this->view->render($response, 'auth/user.twig', [
    'user' => $request->getAttribute('user')
  ]);
}

if I use this

use Slim\Routing\RouteContext;
// ...

$routeArguments = RouteContext::fromRequest($request)
    ->getRoute()
    ->getArguments();

foreach ($routeArguments as $key => $argument) {
  if (!is_null($model = $routeToModel[$key])) {
    $request = $request->withAttribute($key, $model::find($argument));
  }
}

and do

var_dump($request->getAttribute('user'));

it shows the argument value not the result of

$model::find($argument)

but if I use

$request = $request->withParsedBody([
  $key => $model::find($argument)
]);

It works fine, I just don’t understand why.