NGrdanjski
NGrdanjski

Reputation: 151

return new Response return empty data

In cotroller i have getVilla metod which return json response. I get one villa by id from database in $villa variable, and this work fine. When i print_r($villa) i have villa object with all data. But when i push $villa in response with json_encode: json_encode(['villa' => $villa]), villa is empty...

villa: {}
 /**
     * @Route("/ajax/{id}", name="app_post_front_ajax_villa")
     * @param $id
     * @param EntityManagerInterface $em
     * @return Response
     */
    public function getVilla($id, EntityManagerInterface $em): Response
    {

        $repository = $em->getRepository(Villa::class);
        $villa = $repository->findOneBy(['id' => $id]);

        return new Response(json_encode([
            'villa' => $villa,
        ]));
    }

Upvotes: 2

Views: 4660

Answers (1)

Dylan KAS
Dylan KAS

Reputation: 5673

You are returning a json response from a response so you should use JsonResponse instead:

use Symfony\Component\HttpFoundation\JsonResponse;

//...

return new JsonResponse([
            'villa' => $villa,
        ]);

However, your array contain an object $villa, not an array. So you should either make a new array from your villa object or serialize it.

The easy way would be to make a new array from villa :

public function getVilla($id, EntityManagerInterface $em): Response
    {

        $repository = $em->getRepository(Villa::class);
        $villa = $repository->findOneBy(['id' => $id]);

        if($villa){
            $villaArray['id'] = $villa->getId();
            $villaArray['cityNameOrSomething'] = $villa->getCityName();
            //Do the same for other attribute you want to get in your json
        }else{
            $villaArray = [];
        }
        return new Response([
            'villa' => $villaArray,
        ]);
    }

The other way would be to use the serializer component so that you do not have to make a new array. Just follow the Symfony Documentation on the usage to find the one you want to use.

Upvotes: 2

Related Questions