I'm trying to return the result of an API request (using Postman) in Symfony.
Here is my relevant controller code:
/**
* @Route("/apis/login", name="api_login")
*/
public function login(Request $request, UserRepository $userRepository): Response
{
$cin = json_decode($request->getContent(),true)["cin"];
$password = json_decode($request->getContent(),true)["password"];
$user = $userRepository->findOneBy(['cin'=>$cin, 'password'=>$password]);
if($user!=null){
return new JsonResponse(json_encode($user));
}else{
return new JsonResponse("false");
}
}
And this is the request body:
However, this is what I get as a result:
In my code, if I change this line return new JsonResponse(json_encode($user));
to this one return new JsonResponse(serialize($user));
, I get this:
Which proves that the returned object is not empty. Any idea how to fix that?
I've fixed it! I've just converted the user object to an array. So, I've changed my code like so:
/**
* @Route("/apis/login", name="api_login")
*/
public function login(Request $request, UserRepository $userRepository): Response
{
$cin = json_decode($request->getContent(),true)["cin"];
$password = json_decode($request->getContent(),true)["password"];
$user = $userRepository->findOneBy(['cin'=>$cin, 'password'=>$password]);
if($user!=null){
$arr = (array) $user;
foreach($arr as $k=>$v){
$newkey = substr($k,17);
$arr[$newkey] = $arr[$k];
unset($arr[$k]);
}
return new JsonResponse($arr);
}else{
return new JsonResponse("false");
}
}