How to get current route?

I have tried the following method. But it returns null. What do I do?

use Slim\Http\Request;
use Slim\Http\Response;
use Slim\App;

$app = new App([
‘settings’ => [
// Only set this if you need access to route within middleware
’determineRouteBeforeAppMiddleware’ => true
]
])

// routes…
$app->add(function (Request $request, Response $response, callable $next) {
$route = $request->getAttribute(‘route’);
$name = $route->getName();
$groups = $route->getGroups();
$methods = $route->getMethods();
$arguments = $route->getArguments();

// do something with that information

return $next($request, $response);

});

I have just tried the following code and it works like a charm:

<?php
// index.php

require 'vendor/autoload.php';

use Slim\Http\Request;
use Slim\Http\Response;
use Slim\App;

$app = new App([
    'settings' => [
        // Only set this if you need access to route within middleware
        'determineRouteBeforeAppMiddleware' => true,
    ]
]);

// routes...
$app->add(function (Request $request, Response $response, callable $next) {
    $route = $request->getAttribute('route');

    var_dump($route->getMethods());

    return $next($request, $response);

});

$app->get('/', function (Request $request, Response $response) {
    $response->write('from home');
});
$response = $app->run();

Output:

array (
  0 => 'GET',
)
from home

not working.

$name = $route->getName();
is still null.

I use this code in my app:

$route = $request->getAttribute('route');
$rName = $route ? $route->getName() : null;

If this returns null, then this means that your request does not match an existing route (basically this means you’re having a 404 condition).

1 Like

Did you exactly copy my code?

Can you show your route?

$settings = [
‘settings’ => [
‘determineRouteBeforeAppMiddleware’ => true,
‘displayErrorDetails’ => SLIM_DISPLAY_ERROR_DETAILS
]
];
$app = new Slim\App($settings);

$app->add(function ($request, $response, $next) {
$route = $request->getAttribute(‘route’);

$rName = $route ? $route->getName() : null;

error_log($rName);//not working, still null, other methods like getMethods works...

$uri=$request->getUri();//this works
$path=$uri->getPath();//this works

$response = $next($request, $response);
return $response;

});

$app->get(’/hello/{name}’, function ($request, $response, $args) {
$response->withJson(array(“Hello”=>$args[‘name’]));
return $response;
});

And thank you Joe for helping :slight_smile:

You didnt give your route a name … So you cannot retrieve it.

Call setName on the route:

$app->get('/hello/{name}', function ($request, $response, $args) {
    $response->withJson(array("Hello"=>$args['name']));
    return $response;
})->setName('hello');

ohhhh!!! that works.
But is there any way to get ‘/hello/{name}’ directly without setting the name?

does getPattern what you are looking for?

You are the best!!! It works!!!