I'm having some trouble to insert data on a One to Many relationship using Eloquent. When I pass an array to the object as the documentation states an error is thrown and when I echo $ex->getMessage() only the index of the array I'm trying to pass("number") is printed. Does anybody have any idea why this happens?
public static function insert(Request $request, Response $response) {
try {
$data = $request->getParsedBody();
$user = new \User;
$user->name = $data['name'];
$user->flag = $data['flag'];
$user->login = $data['login'];
$user->password = md5(SALT . $data['password']);
//$user->save();
foreach ($data['phoneNumbers'] as $key => $number) {
$phonenumber[$key] = new \Phonenumber(array("number" => $number));
}
$user->phonenumbers()->saveMany($phonenumber);
$meta = Helper::retornaMetaArray(Enum::SUCS_STS, Enum::CREATED, 201);
return $response->withCustomJson(null, $meta);
} catch (Exception $ex) {
echo $ex->getMessage();
}
}
This is what I'm sending on the request body:
{
"name": "Jon Snow",
"login": "jon",
"password": "ghost",
"flag": "1",
"phoneNumbers": ["(82) 99178-1066", "(82) 99303-9037"]
}
Related
I have the following blocks of code
try {
$data = Checklist::where('setupStatus', true)->whereJsonContains('workspaceRegions', $regionID)->orderBy('id', 'desc')->paginate(5);
return response()->json([
'data' => $data
], 200);
} catch (\Throwable $th) {
return $th;
}
This works as expected and returns the correct checklists.
So then I did the same in the next block, but this time I have to iterate through and array to get the id values to search for. This always return an empty array though
$company = Auth::user()->company;
try {
$hodIDs = CompanyRoles::where('hod', true)->get();
$hods = [];
foreach ($hodIDs as $option) {
$id = strval($option->id);
$hods = User::where('companyID', $company->id)->whereJsonContains('companyRoles', $id)->with('employee')->get();
}
return response()->json([
'message' => 'success',
'hods' => $hods
], 200);
} catch (\Throwable $th) {
return $th;
}
The 'companyRoles' column is an array that contains something like ["1","2"]
How can I return each user with and hodID within the companyRoles column array?
The following gives me what I want, but this feels a bit like a hack.
$hods = [];
foreach ($hodIDs as $option) {
$id = strval($option->id);
$user = User::where('companyID', $company->id)->whereJsonContains('companyRoles', $id)->with('employee')->first();
if ($user) {
array_push($hods, $user);
}
}
Thanking you in advance
I have a function
public function getCandidates($candidateEmail)
{
try {
$moduleIns = ZCRMRestClient::getInstance()->getModuleInstance('Candidats');
$response = $moduleIns->searchRecordsByEmail($candidateEmail, 1, 1);
$candidates = $response->getResponseJSON();
return $candidates;
} catch (ZCRMException $e) {
echo $e->getMessage();
echo $e->getExceptionCode();
echo $e->getCode();
}
}
And I use this function like that :
$obj = new ZohoV2();
$response = $obj->getCandidates($request->email);
$candidate = $response['data'][0];
return response()->json([ 'status' => 'success', 'candidate' => $candidate ], 200);
Theses functions allows me to retrieve a user from a database of a CRM.
But when the user does not exist, he sends me a 500 error.
{message: "No Content", exception: "zcrmsdk\crm\exception\ZCRMException",…}
exception: "zcrmsdk\crm\exception\ZCRMException"
file: "/home/vagrant/CloudStation/knok/myath/myath-app/vendor/zohocrm/php-sdk/src/crm/api/response/BulkAPIResponse.php"
line: 61
message: "No Content"
trace: [{,…}, {,…}, {,…}, {,…}, {,…}, {,…},…]
How to intercept this error so that I can process it as I want and send an error message ?
Thank you
Remove the try/catch from your first code block
public function getCandidates($candidateEmail)
{
$moduleIns = ZCRMRestClient::getInstance()->getModuleInstance('Candidats');
$response = $moduleIns->searchRecordsByEmail($candidateEmail, 1, 1);
$candidates = $response->getResponseJSON();
return $candidates;
}
And move it to the second code block (I assume it's the controller)
$obj = new ZohoV2();
try {
$response = $obj->getCandidates($request->email);
} catch (ZCRMException $e) {
return response()->json(['status' => 'failed', 'error' => $e->getMessage()], 404);
}
$candidate = $response['data'][0];
return response()->json([ 'status' => 'success', 'candidate' => $candidate ], 200);
How can I catch Notification::send exception? This notification works fine, but I want to add some admin page for watching status. Notification::send method always return null regardless success or not.
Full code now:
namespace App\Listeners;
use App\Events\SendUserNotification;
use Illuminate\Support\Facades\Notification;
use App\Models\LogNotification;
class SendUserNotificationListener
{
public function handle(SendUserNotification $event)
{
$users = $event->users;
$notification = $event->notification;
$logData = [];
try {
$send = Notification::send($users, $notification); // returned null
$status = "success";
} catch (\Exception $exception) {
$status = "error";
}
foreach ($users as $user) {
$logData[] = [
"user_id" => $user->id,
"type" => $notification->getType(),
"status" => $status,
"created_at" => now(),
"updated_at" => now(),
];
}
LogNotification::insert($logData);
}
}
This code cant catch any exceptions in Notification::send method.
use apigility to get json response in postman
when i send post request in postman and return response like this
{
"\u0000*\u0000version": null,
"\u0000*\u0000contentSent": false,
"\u0000*\u0000recommendedReasonPhrases": {
"100": "Continue",
"101": "Switching Protocols",
"102": "Processing",
"200": "OK",
"201": "Created",
"202": "Accepted",
"203": "Non-Authoritative Information",
"204": "No Content",
"205": "Reset Content",
"206": "Partial Content",
.
.
.
"508": "Loop Detected",
"511": "Network Authentication Required"
},
"\u0000*\u0000statusCode": 200,
"\u0000*\u0000reasonPhrase": null,
"\u0000*\u0000headers": {},
"\u0000*\u0000metadata": [],
"\u0000*\u0000content": "{\"success\":\"this is test\"}",
"_links": {
"self": {
"href": "http://xxxxx/xxxxx/public/userapi"
}
}
my code in userapiresource.php, using get table data and return it also output like this
public function create($data)
{
$response=new HttpResponse;
$response->setContent(\Zend\Json\Json::encode(array('success'=>"this is test")));
return $response;
}
got it in return response in apigility:
so change my code in userapiResource.php
public function create($data)
{
$client = new Client();
$client->setUri('http://xxxx/xxxx/public/mob-app/client/update');
// set some parameters
$client->setParameterPost(array('userid'=> $data->userid,'price'=>$data->price));
// POST request
$client->setMethod('POST');
$respons=$client->send();
$respons->getContent();
$returnArray = [];
$final_array = [
'content' => json_decode($respons->getContent())
];
$returnArray['data'] = $final_array;
$returnArray['success'] = 'true';
$returnArray['reason'] = '';
return $returnArray;
}
I have two controllers, one that record the modified entities and put them in a session:
public function update_accountAction(Request $request)
{
Try
{
$code = $request->request->get('code');
$name = $request->request->get('name');
$em = $this->getDoctrine()->getManager();
$repo = $em->getRepository('NRtworksChartOfAccountsBundle:Accounttree');
$to_change = new Accounttree();
$to_change = $repo->findOneByCode($code);
$to_change->setName($name);
$to_change->setCode($code);
$session = $this->getRequest()->getSession();
$entity_to_update = $session->get('entity_to_update');
$counter = $session->get('number_of_changes');
$entity_to_update[] = $to_change;
$counter = $counter +1;
$session->set('number_of_changes',$counter);
$session->set('entity_to_update',serialize($entity_to_update));
$response = array("code" => 100, "success" => true, "modified" => $entity_to_update);
return new Response(json_encode($response));
}
Catch(Exception $e)
{
$response = array("code" => 100, "success" => false, "error" => $e);
return new Response($response);
}
}
And another one that loop on the results, and if it's actually one of the desired object persist it. Finally I flush.
public function save_changesAction()
{
Try
{
$em = $this->getDoctrine()->getManager();
$session = $this->getRequest()->getSession();
$entity_to_update = unserialize($session->get('entity_to_update'));
foreach($entity_to_update as $account)
{
if($account->getId())
{
$em->persist($account);
echo $account->getId();
}
else
{
echo "error";
}
}
$em->flush();
$response = array("code" => 100, "success" => true, "modified" => $account->getId());
return new Response(json_encode($response));
}
Catch(Exception $e)
{
$response = array("code" => 100, "success" => false, "error" => $e);
return new Response($response);
}
}
So the result of this is:
ContextErrorException: Notice: Undefined index: 000000007a60b041000000007ae6afd8 in /home/eagle1/www/Symfony24/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php line 2852
I don't understand why, because it seems that I get back a fully functional object (I can execute its functions, access its property and it seems also that the persist is working...
Somebody knows the answer ?
When you pull object from session, it is not managed by doctrine. You have to merge it back to notify entity manager about it.
if($account->getId())
{
$account = $em->merge($account);
$em->persist($account);
echo $account->getId();
}
Doctrine has manual section for Entities in the Session