PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, February 6, 2022

[FIXED] Symfony 5 Route name in Controller

 February 06, 2022     symfony, symfony5     No comments   

Issue

How do I obtain the name of the current route in the controller in Symfony 5? When I try this I get NULL:

$this->Request = Request::createFromGlobals();
$route = $this->Request->attributes->get('_route');

var_dump($route);

Solution

It's not recommended to create request inside your controller. Preferred way of obtaining already created Request is DI and autowiring:

// src/Controller/BlogController.php
namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

class BlogController extends AbstractController
{
    /**
     * @Route("/blog", name="blog_list")
     */
    public function list(Request $request)
    {
        $routeName = $request->attributes->get('_route');
        $routeParameters = $request->attributes->get('_route_params');

        var_dump($routeName);
    }
}

This request is processed by Symfony HttpKernel and filled with additional information.

More info: https://symfony.com/doc/current/routing.html#getting-the-route-name-and-parameters

How did it get there: https://github.com/symfony/symfony/blob/b2609c4bae69ca383b97cb520da2ed9be1c48449/src/Symfony/Component/Routing/Matcher/UrlMatcher.php#L217



Answered By - Pavol Velky
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing