How do I convert an object to an array in php - php

Hi I have been trying to figure out how to convert an object to an array I have tried using json_decode but that doesn't turn it into a nested array but it looks like the picture below becuase I am using angular I need everything to be in an array can someone tell me what I am doing wrong
What the data currently looks like when I use json_decode
The PHP function:
public function getForm(Request $request)
{
try
{
$id = $request->input('id');
$form = admin_form::find($id);
if($form) {
$form = admin_form::where('id',$id)->with('fields')->first();
$res['Message'] = "Success";
$res['Status'] = true;
$res['results'] = json_decode($form, true);
return response($res, 200);
} else {
$res['status'] = false;
$res['message'] = "Form not found";
return response($res, 404);
}
} catch(\Illuminate\Database\QueryException $ex) {
$res['status'] = false;
$res['message'] = $ex->getMessage();
return response($res, 500);
}
}

create a variable and store json init and pass response as parameter
var test = json.parse(response);

As I know you don't need to convert object to array, cause you can iterate over it in ng-repeat. Try to use the following syntax:
<div ng-repeat="(key, val) in results">{{key}} => {{val}}</div>
According to ng-repeat documentation

Just for anyone having the problem I had this is how I sloved it
public function getForm(Request $request)
{
try
{
$id = $request->input('id');
$form = admin_form::find($id);
if($form) {
$form = admin_form::where('id',$id)->with('fields')->first();
$res['Message'] = "Success";
$res['Status'] = true;
$res['results'] = [$form->getAttributes()];
return response($res, 200);
} else {
$res['status'] = false;
$res['message'] = "Form not found";
return response($res, 404);
}
} catch(\Illuminate\Database\QueryException $ex) {
$res['status'] = false;
$res['message'] = $ex->getMessage();
return response($res, 500);
}
}
The reason this worked for me was because the $form is an object with all of the information about what I am trying to get and when you do a dd($form) all of the information that it gets from the DB is stored in the attributes array and lumen has a getAttributes() function and from there I put them into [] to get an array
But if you have a relationship with another table then don't use getAttributes just use the [] braces

Related

Laravel 8 not finding "tag" from package "\Conner\Tagging\Taggable;"

The code works perfectly when I want to create a new tag from scratch, but when $skillsQuery->count() > 0 and enters in the if statement. It prints...
Method Illuminate\Database\Eloquent\Collection::tag does not exist.
How can I update tags using this package?
Controller
<?php
public function storeSkills(Request $request)
{
$id = auth()->user()->id;
$skillsQuery = Skill::where('created_by', $id)->get();
// If skill exists
if ($skillsQuery->count() > 0) {
$input = $request->all();
$tags = explode(", ", $input['name']);
// $skill = Skill::create($input);
$skillsQuery->tag($tags);
$skillsQuery->created_by = $id;
if ($skillsQuery->save()) {
return redirect()->route('profile')->with('success', 'Skills updated successfully');
} else {
return redirect()->route('profile')->with('error', 'Error updated your Skills!');
}
} else {
$input = $request->all();
$tags = explode(", ", $input['name']);
$skill = Skill::create($input);
$skill->tag($tags);
$skill->created_by = $id;
if ($skill->save())
return redirect()->route('profile')->with('success', 'Skills stored successfully');
else {
return redirect()->route('profile')->with('error', 'Error storing your Skills!');
}
}
}
The result of calling ->get() on a Illuminate\Database\Query is that you will receive an instance of a Illuminate\Database\Collection, which does not contain a ->tag() method. Even if it was a query (by removing ->get()) this still would not work, as you can't call a relationship method off of a collection.
If instead you loop over the skillsQuery then you will receive an instance of a Model object which then allows you to access functions and/or relationships off of it:
$skillsQuery->each(function ($skill) use ($tags) {
$skill->tag($tags); // or perhaps ->retag($tags); here
});

Slim query parameter

I want to add a query parameter in my GET Route, which is this one:
$app->get('/rooms', function (ServerRequestInterface $request, ResponseInterface $response, $args) {
try {
$room = new \Riecken\PBS\controller\RoomController();
$result = $room->getRoomsWithDetails();
$response = $response->withJson($result);
$response = $response->withStatus(200);
return $response;
}catch(Exception $e) {
$response->getBody()->write($e->getMessage());
return $response->withStatus($e->getCode());
}
});
What I want to do is that I only want to execute this function when I type "expandAll".
I googled it and I could find something in the Slim documentation:
https://www.slimframework.com/docs/v3/objects/request.html
But I dont know how to implement it.
So in my case:
If "expandAll" I want to execute the function you see above (getRoomWithDetails(), else I want to execute another function.
Is that possible?
Thanky you very much!
You could just pass the required query parameters to getRoomsWithDetails or you just add a if condition.
Example
$app->get('/rooms', function (ServerRequestInterface $request, ResponseInterface $response, $args) {
try {
$expandAll = $request->getParam('expandAll');
$room = new \Riecken\PBS\controller\RoomController();
if ($expandAll) {
$result = $room->getRoomsWithDetails();
} else {
$result = $room->anotherMethod();
}
$response = $response->withJson($result);
$response = $response->withStatus(200);
return $response;
} catch(Exception $e) {
$response = $response->withJson(['error' => ['message' => $e->getMessage()]]);
return $response->withStatus(500);
}
});

When I update my data with PHP CodeIgniter, It gives an error. But data is saving

I am using 'CodeIgniter-3.1.3'. When I update my data, it gives an error as follow. But my data is saving in database. I can't find what is the issue. Is there any issue with my model function related to version..?
Error : Fatal error: Call to undefined method CI_DB_mysqli_driver::_error_number()
In Controller
public function saveUpdateData(){
$updateDataArray = array(
"fname" => $_POST['fname'],
"lname" => $_POST['lname'],
"username" => $_POST['user'],
"userlevel" => $_POST['userlevel'],
"contact" => $_POST['contact_no']
);
$whereArr=array("user_id"=>$this->input->post("user_id"));
$rst = $this->MyModel->updateData("admin", $updateDataArray, $whereArr);
if ($rst) {
echo "updated";
}
else{
echo "error";
}
}
In model
function updateData($tablename, $data_arr, $where_arr) {
try {
$this->db->update($tablename, $data_arr, $where_arr);
$report = array();
$report['error'] = $this->db->_error_number();
$report['message'] = $this->db->_error_message();
return $report;
} catch (Exception $err) {
return $err->getMessage();
}
}
enter image description here
Do like this
In Model
function updateData($tablename, $data_arr, $where_arr)
{
if (!$this->db->update($tablename, $data_arr, $where_arr)) {
$result = $this->db->error();
}
else {
return TRUE;
}
}
In Controller
$rst = $this->MyModel->updateData("admin", $updateDataArray, $whereArr);
if ($rst == TRUE) {
echo "updated";
}
else{
print_r($rst);
}
Read Error Handling Codeigniter
In CodeIgniter 3+, you can get errors with error no and messages as by using the following:
$error = $this->db->error();
Reference: Handling Query Errors in CodeIgniter
The functions you are trying to access have been deprecated.
Replace:
$this->db->_error_number()
$this->db->_error_message()
With:
$this->db->error()
The new function will return an array with both the error number and message.
Refer to this CodeIgniter page:
https://www.codeigniter.com/userguide3/changelog.html?highlight=_error_number

How can I use db transaction in laravel?

I try this :
public function destroy($id)
{
DB::beginTransaction();
try {
$product = $this->product_repository->find($id);
$result = $product->categories()->detach();
if($result) {
list($status,$instance) = $this->product_repository->delete($id);
}
DB::commit();
return ['status'=>true,'data'=>$status];
} catch (\Exception $e) {
DB::rollback();
return ['status'=>false, 'message'=>$e->getMessage()];
}
}
If the code executed, $this->product_repository->delete($id) not work / not success delete.
But this : $product->categories()->detach();, it works / success deleted.
How to if delete product failed, delete category also failed?
You can't add return statement inside transaction that halts entire process and DB::rollback() is executed.
To switch the return, You can define a boolean variable and make false while you catch exception.
Like this:
public function destroy($id)
{
$success = true;
DB::beginTransaction();
try{
// Your Code
$product = $this->product_repository->find($id);
$result = $product->categories()->detach();
if($result) {
list($status,$instance) = $this->product_repository->delete($id);
}
DB::commit();
}catch(\Exception $e){
DB::rollback();
$success = false;
}
if($success){
// Return data for successful delete
}
else{
// Return data for unsuccessful delete
}
}
Hope you understand.
You can use it like this:
$returnResult = [];
DB::beginTransaction();
try {
...
DB::commit();
$returnResult['status'] = true;
$returnResult['data'] = $status;
} catch (...) {
...
DB::rollback();
$returnResult['status'] = true;
$returnResult['message'] = $e->getMessage();
}
return $returnResult;

How to save embedded forms in symfony 1?

I have a form which represnts single answer object (this is standard propel generated form I have not changed much there only some validation rules) and another form that represents a collection of answers code as below:
class BbQuestionAnswersForm extends sfForm {
public function __construct($defaults = array(), $options = array(), $CSRFSecret = null) {
parent::__construct($defaults, $options, $CSRFSecret);
}
public function configure() {
if (!$questions = $this->getOption('questions')) {
throw new InvalidArgumentException('The form need array of BbExamQuestion objects.');
}
if (!$taker = $this->getOption('taker')) {
throw new InvalidArgumentException('The form need BbExamtaker object.');
}
if (!$user = $this->getOption('questions')) {
throw new InvalidArgumentException('The form need sfGuardUser object.');
}
foreach($questions as $question) {
$answer = new BbExamAnswer();
$answer->setBbExamQuestion($question);
$answer->setBbExamTaker($taker);
$answer->setCreatedBy($user);
$answer->setUpdatedBy($user);
$form = new BbExamAnswerForm($answer, array('question' => $question));
$this->embedForm($question->getId(), $form);
}
$this->widgetSchema->setNameFormat('solve[%s]');
}
}
Everything(validation, display) goes fine with this form until I try to save it. Part of action which trying to save the form:
...
$this->form = new BbQuestionAnswersForm(null, array('questions' => $this->questions, 'taker' => $this->taker, 'user' => $this->getUser()->getGuardUser()));
if($request->isMethod('post')) {
$this->form->bind($request->getParameter($this->form->getName()));
if($this->form->isValid()) {
if($this->form->save()) {
$this->getUser()->setFlash('success', 'Save goes fine.');
$this->redirect($this->generateUrl('#bb'));
} else {
$this->getUser()->setFlash('error', 'Upps an error occurred.');
}
}
}
When I send valid form I receive "Call to undefined method BbQuestionAnswersForm::save()" error.
I tried to write this method like this:
public function save() {
$conn = Propel::getConnection(ZlecPeer::DATABASE_NAME);
$conn->beginTransaction();
try{
foreach($this->getEmbeddedForms() as $form) {
$form->save();
}
$conn->commit();
} catch(Exception $e) {
$conn->rollback();
echo 'upps something goes wrong';
die($e->getMessage());
return false;
}
return true;
}
but it doesnt work, I receive exception without any message.
What am I doing wrong, how to make save method work?
I believe your BbQuestionAnswersForm is extending the wrong object. It should extend BaseFormDoctrine or possibly BaseBbQuestionAnswersForm if you are using the framework correctly.
Edit: Just noticed you are using propel but it should be the same thing. Try:
class BbQuestionAnswersForm extends BaseBbQuestionAnswersForm
and less likely:
class BbQuestionAnswersForm extends BaseFormPropel
Save method should looks like this:
public function save($con = null) {
if (null === $con) {
$con = Propel::getConnection(BbExamAnswerPeer::DATABASE_NAME);
}
$con->beginTransaction();
try{
foreach($this->embeddedForms as $name => $form) {
if(!isset($this->values[$name]) || !is_array($this->values[$name])) {
continue;
}
if($form instanceof sfFormObject) {
$form->updateObject($this->values[$name]);
$form->getObject()->save($con);
$form->saveEmbeddedForms($con);
} else {
throw new Exception('Embedded form should be an instance of sfFormObject');
}
}
$con->commit();
} catch(Exception $e) {
$con->rollBack();
throw $e;
return false;
}
return true;
}

Categories