How do I get arguments from the URL? in other words, what is the equivalent of the arg() function of Drupal 7 and previous versions?


As reported in the arg() is deprecated and will be removed change record, the Drupal 8 (procedural) equivalent of arg() is the following one.

$current_path = \Drupal::service('path.current')->getPath();
$path_args = explode('/', $current_path);

As the change record makes notice, not all the times that is the correct code to use. Depending from the context, you should use code similar to the following one.

  • Check if a path is for an administrative page

    if (\Drupal::service('router.admin_context')->isAdminRoute()) {
      // Your code.
  • Add CSS or JavaScript conditionally, basing on the page being visited

    function mymodule_page_attachments(array &$attachments) {
      if (\Drupal::routeMatch()->getRouteName() == 'my.route') {
        $attachments ['#attached']['library'][] = 'my_module/my_library'; // you'll need to define in mymodule.libraries.yml
  • Load the currently viewed node

    $node = \Drupal::routeMatch()->getParameter('node');

Notice that in the first and last case, in Drupal 7 you should not use arg(), but respectively path_is_admin() and menu_get_object(). The typical beginner-Drupal-developer error is using arg() also in those cases.


arg() is deprecated in drupal 8, however we can get values like arg() function does in drupal 7 & 6 by mentioned

$path = \Drupal::request()->getpathInfo();
$arg  = explode('/',$path);
print_r($arg); exit(); 

The output would be parameters in url except basepath or (baseurl),

   [0] => 
   [1] => node
   [2] => add

Please see https://www.drupal.org/node/2150267

Drupal 7

$query = $_GET['q']; // query string param
$myparam = $_POST['myparam']; // form param
$request_method = $_SERVER['REQUEST_METHOD']; // server variable
$mycookie = $_COOKIE['mycookie']; // cookie

In Drupal 8

$query = \Drupal::request()->query->get('q'); // query string param
$name = \Drupal::request()->request->get('name'); // form param
$request_method = \Drupal::request()->server->get('REQUEST_METHOD'); // server variable
$mycookie = \Drupal::request()->cookies->get('mycookie'); // cookie

I'm the maintainer for the d7d8 module, which seeks to port drupal 7 functions into drupal 8/9 to make development easier.

We have an arg() drop-in replacement for d8/9. It's just d7d8_arg()

See: https://www.drupal.org/project/d7d8

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.