Symfony4 Annotation routing does not work

okey_on picture okey_on · Jun 7, 2018 · Viewed 11k times · Source

I just started learning Symfony. I am following this official tutorial exactly. Routing works fine when done with config/routes.yaml but on using annotations:

namespace App\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Annotation\Route;

class LuckyController
{

    /**
     *  @Route("/lucky/number")
     */
    public function number(){

        $number = mt_rand(0, 100);

        return new Response(
            '<html><body><h1>MyLucky Number: ' . $number . '</h1></body></html>'
        );
    }
}

I get this error:

    Exception thrown when handling an exception
(Symfony\Component\Config\Exception\FileLoaderLoadException: [Semantical Error]
 The annotation "@Symfony\Component\Annotation\Route" in method 
App\Controller\LuckyController::number() does not exist, or could not be auto-loaded
 in C:\wamp\vhosts\mysymfony4\config/routes\../../src/Controller/ (which is
 being imported from "C:\wamp\vhosts\mysymfony4\config/routes/annotations.yaml"). Make sure
 annotations are installed and enabled.)

Answer

okey_on picture okey_on · Jun 9, 2018

I found out my mistake. I used the wrong namespace for routing.

use Symfony\Component\Annotation\Route;

It should have been:

use Symfony\Component\Routing\Annotation\Route;

EDIT: I wanted to delete this question but the system wouldn't let me.