0

Hi I'm having troubles getting a list of all "blog tag" entities in the index function of my controller.

I tried using normalizer groups but somehow I still get a circular reference error. I expect my controller to output a list of blog tags, by id and name.

This is my controller:

    #[Route('/', name: 'api_blogtag_index', methods: ['GET'])]
    #[IsGranted('IS_AUTHENTICATED')]
    public function index(BlogtagRepository $blogtagRepository): Response
    {
        return $this->json([
            'tags' => $blogtagRepository->findAll(),
            Response::HTTP_OK, [], [
                AbstractNormalizer::GROUPS => ['show_blogtag']
            ]
        ]);
    }

And this is the blog tag entity class:

#[ORM\Entity(repositoryClass: BlogtagRepository::class)]
class Blogtag
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column]
    #[Groups(['show_blogtag'])]
    private ?int $id = null;

    #[ORM\Column(length: 255, unique: true)]
    #[Groups(['show_blogtag'])]
    private ?string $name = null;

    #[ORM\ManyToMany(targetEntity: Blog::class, inversedBy: 'blogtags')]
    private Collection $blogs;
  • add an `[#Ignore]` to the `Collection $blogs` if you dont need them. if you need the blog relation in the json response then ignore the blogtag in the blog entity. (if you do this with groups you can hide or include them as needed) – Rufinus Jan 06 '23 at 13:34

1 Answers1

0

Circular reference is an error that appears when an object refers to itself, directly. This problem has already been solved, here you will find an answer of your problem. You can learn more on official documentation

  • I already found that question but I still cannot get it to work. From what I understand is that I have to use Group Annotations. But I use group annotations using a normalizer but it still doesn't work. – Martijn van Sliedregt Jan 04 '23 at 20:34
  • You should use them in each entity involved in the query you are performed, seeing your question, i think you only used them in one entity – Yolserve Ngoma Jan 05 '23 at 07:39