I am getting data from database model and want to return in json format, but it returns empty array, but when i use dump for variable that contains objects data then it return the actual data.
Here is the code for getting data from object
$user = $this->getUser();
$bookings = $this->getDoctrine()->getRepository(Trip::class)
->findBy(['customer' => $user], ['id' => 'DESC']);
here i return it in json form
return new JsonResponse(['bookings' => $bookings]);
It display on screen that array is empty.
i use dd to check whether data is comming or not
$user = $this->getUser();
$bookings = $this->getDoctrine()->getRepository(Trip::class)
->findBy(['customer' => $user], ['id' => 'DESC']);
dd($bookings);
It returns
kindly help me out how to overcome this issue
My Answer:
>getDoctrine()->getRepository(User::class)->findAll();
And here is the code for returning data in JSON format:
php
return $this->json($user);
If this code is returning an empty array, it could be because the User objects are not being properly serialized to JSON. You can try manually serializing the data before returning it:
php
$userData = [];
foreach ($user as $u) {
$userData[] = [
'id' => $u->getId(),
'name' => $u->getName(),
// Add more fields as needed
];
}
return $this->json($userData);
This code will loop through each User object, extract the necessary data, and store it in an array that can be easily serialized to JSON.
Rate this post
5 of 5 based on 3211 votesComments