Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty JSON Return - Symfony3

Tags:

json

php

symfony

I am a beginner in PHP & Symfony 3 and I have a problem: json_encode returns empty objects. You can check the image and code below.

/**
 * @Rest\Get("/user")
 */
public function getAction()
{
    $restresult = $this->getDoctrine()->getRepository('AppBundle:User')->findAll();
    if ($restresult === null) {
        return new View("there are no users exist", Response::HTTP_NOT_FOUND);
    }

    return new Response(json_encode($restresult), Response::HTTP_OK);
}

enter image description here

like image 732
Olivio Avatar asked Oct 26 '25 16:10

Olivio


1 Answers

I think It's because the findAll() method return an array of object, you should personalize your method in the repository to get an array result,

public function findAllArray()
 {
     $qb = $this
         ->createQueryBuilder('u')
         ->select('u');
     return $qb->getQuery()->getArrayResult();
 }

Another thing, in Symfony you can use New JsonResponse to send Json datas

return new JsonResponse($restresult);
like image 63
Smaïne Avatar answered Oct 28 '25 05:10

Smaïne



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!