Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unknown Entity namespace alias 'entity name'

Tags:

symfony5

I looked at the similar questions but couldn't find a solution to my problem.

In my project symfony, I get the information from my database with this code

$backup = $this->getDoctrine()->getRepository(LocalInformations::class)->findByRegion('west');

But only, the LocalInformation entity, its region attribute and the value of this attribute 'west', are variable and obtained from an ajax request. So I have

$value = trim($data['value']);
$property = trim($data['property']);
$entity = trim($data['entity']);
 
$class = ucfirst($entity) . '::class';
$findByProperty = 'findBy' . ucfirst($property);
 
dump($class);
dump($property);
dump($value);
 
$backup = $this->getDoctrine()->getRepository($class)->$findByProperty($value);

I am getting the following error: 'Unknown Entity namespace alias 'LocalInformations'.

And when I comment the last line, the dumps give me "LocalInformations::class", "region", "west"

I noticed the first problem, I have

$backup = $this->getDoctrine()->getRepository("LocalInformations::class")->findByRegion('west');

instead of

$backup = $this->getDoctrine()->getRepository(LocalInformations::class)->findByRegion('west');

"LocalInformations::class" is a string not a class name. Now the problem becomes, how do you remove quotes around a string?

like image 843
DONGMO BERNARD GERAUD Avatar asked Aug 06 '26 06:08

DONGMO BERNARD GERAUD


1 Answers

The ::class wouldn't be so helpful since you would need to have the class in your use statements for this to work. The ::class would normally return the FQCN so why not using it directly.

$class = sprintf('\App\Entity\%s', ucfirst($entity));
$findByProperty = 'findBy' . ucfirst($property);
 
$backup = $this->getDoctrine()->getRepository($class)->$findByProperty($value);

Make sure to use the proper namespace for your entities...

Also, make sure to validate that the user should be able to request the entity. Never trust user input as it can be forged easily in most cases.

like image 184
Julien B. Avatar answered Aug 09 '26 15:08

Julien B.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!