My symfony request is returning array with entity object and setstate method.
This is the dump of the array.
array (
0 =>
HealthyLiving\ApiBundle\Entity\User::__set_state(array(
'id' => 1,
'username' => 'admin',
'password' => '123',
'email' => 'batoosay#gmail.com',
'isActive' => false,
)),
)
And here is the code:
public function loginAction()
{
$restresult = $this->getDoctrine()->getRepository('ApiBundle:User')->findAll();
if ($restresult === null) {
return new View("there are no users exist", Response::HTTP_NOT_FOUND);
}
echo '<pre>' . var_export($restresult, true) . '</pre>';die;
return new JsonResponse(
$restresult
);
}
The JsonResponse is empty because of the strange array. How do i convert this array of object to json ?
try to serialize with JMS like this:
$serializer = $this->get('jms_serializer');
return new Response(
$serializer->serialize($restresult, 'json')
);
Related
How do I return the following response format using the code below:
{"data":[],"meta":{"paging":{"links":[],"total":0},"time":0.079}}
The controller code:
public function someMethod()
{
$var=SomeModel::with(['status' => function ($query) {
$query->where('name', 'like', '%Pending Payment%');
}])->get();
return [
'data' => $var,
];
}
Response am getting
{"data":[]}
I was able to solve the problem using Resource Collection
public function toArray($request)
{
return [
'data' => $this->collection,
'meta' => [
'paging' => [
'links'=>[],
'total'=>0,
],
],
'time'=>'',
];
}
$data = Order::query();
// Apply filters and/or sorting to the data query
// ...
$paginator = $data->paginate(5);
$paginatedData = [
'data' => $paginator->items(),
'meta' => [
'paging' => [
'links' => $paginator->links(),
'total' => $paginator->total(),
],
'time' => microtime(true) - LARAVEL_START,
],
];
return response()->json($paginatedData);
When I pass array() through query it got false but when I pass without array then it show success. How can I pass array according to my code?
public function add_employee_post(Request $request){
try{
$http = new \GuzzleHttp\Client();
$employee_no = $request->employee_no;
$name = $request->name;
$nid = $request->nid;
$dob = $request->dob;
$covid_status = $request->covid_status;
$vaccine_certificate = $request->vaccine_certificate;
$official_email = $request->official_email;
$optional_email = array();
if($request->optional_email[0] != null){
foreach (json_decode($request->optional_email[0]) as $key => $email) {
array_push($optional_email, $email->value);
}
}
$official_phone = $request->official_phone;
$optional_phone = array();
if($request->optional_phone[0] != null){
foreach (json_decode($request->optional_phone[0]) as $key => $phone) {
array_push($optional_phone, $phone->value);
}
}
$designation = $request->designation;
$employee_type = $request->employee_type;
$role = $request->role;
$department = $request->department;
$team = $request->team;
$grade = $request->grade;
$level = $request->level;
$avatar = $request->avatar;
$present_address = $request->present_address;
$permanent_address = $request->permanent_address;
$employee_status = $request->employee_status;
$employee_invitation_status = $request->employee_invitation_status;
$response = $http->post('http://localhost:8000/api/v1/employees/create',[
// 'headers' => [
// 'Authorization' => 'Bearer'.session()->get('token.access_token'),
// ],
'query' =>[
'employee_no' => $employee_no,
'name' => $name,
'nid' => $nid,
'dob' => $dob,
'covid_status' => $covid_status,
'vaccine_certificate' => $vaccine_certificate,
'official_email' => $official_email,
'optional_email' => $optional_email,
'official_phone' => $official_phone,
'optional_phone' => $optional_phone,
'designation' => $designation,
'employee_type' => $employee_type,
'role' => $role,
'department' => $department,
'team' => $team,
'grade' => $grade,
'level' => $level,
'avatar' => $avatar,
'present_address' => $present_address,
'permanent_address' => $permanent_address,
'employee_status' => $employee_status,
'employee_invitation_status' => $employee_invitation_status,
]
]);
$result = json_decode((string) $response->getBody(), true);
return $result;
}
catch(\Throwable $e){
return response()->json([
'result' => false,
'message' => 'Something Error!'
]);
}
}
In same code when I comment out $optional_phone and $optional_email , it show success response but when I pass all then it show false result. How I pass an array inside query?
Assume I have an array called (data) and inside my array I have a foreach on products. I need to get each of these product packages inside this (data) array.
Here is what I've tried:
foreach ( $products as $product ) {
$data[] = [
'id' => $product->id,
'packages' => [],
]
foreach ( $product->packageId as $package ) {
$data[]['packages'] = [
'package_id' => $package['id'],
];
}
}
This returns:
- 0 [
id: 977
packages: []
]
- 1 [
packages
package_id: 14
]
- 2 [
packages
package_id: 15
]
I need to return something like this:
- 0 [
id: 977
packages: [
package_id: 14,
package_id: 15
]
]
Update
as #Helioarch and #albus_severus mentioned in they answers that I should create the package array first then include that into the data array
this solution will add the old array of packages in every time the products loops
For Example
product 1 has packages [1,2,3]
product 2 has packages [4,5,6]
in this my case here it will become
product 1 have packages [1,2,3]
product 2 will have packages [1,2,3,4,5,6] <- witch is wrong.
Update 2
Here is my full code
foreach ( $products as $product ) {
$sums = 0;
foreach ( $product->packageId as $package ) {
// Get the total existing inventory
$pckInvSum = $package->pckInventories
->where( 'expiry_date', '<', Carbon::today() )
->where( 'type', 'existing' )->sum( 'amount' );
// Get the total virtual inventory
$pckInvVirtual = $package->pckInventories->where( 'type', 'virtual' )->sum( 'amount' );
// create new array packages to add it to the main json
$packages[] = [
'package_id' => $package['id'],
'package_price' => $package['price'],
'unit_count' => $package['unit_count'],
'existing' => $pckInvSum,
'virtual' => $pckInvVirtual
];
$sums += $package->pckInventories->sum( 'amount' );
}
$data[] = [
'id' => $product->id,
'product_category_id' => $product->product_category_id,
'child_category_id' => $product->child_category_id,
'child_category_two_id' => $product->child_category_two_id,
'child_category_three_id' => $product->child_category_three_id,
'supplier_id' => $product->supplier_id,
'supplier_name' => $product->supplier->contact_name,
'option_category_id' => $product->option_category_id,
'tax_id' => $product->tax_id,
'barcode' => $product->barcode,
'low_price' => $product->low_price,
'image' => $product->image,
'cost' => $product->cost,
'name_ar' => $product->translations[0]->name,
'name_en' => $product->translations[1]->name,
'details_ar' => $product->translations[0]->details,
'details_en' => $product->translations[1]->details,
'sumInv' => $sums,
'campaign' => [
'id' => $product->campaign[0]->id,
'product_id' => $product->campaign[0]->product_id,
'price' => $product->campaign[0]->price,
'purchasesLimits' => $product->campaign[0]->purchasesLimits,
],
'packages' => $packages,
];
You should create the package array first then include that into the data array like so:
foreach ( $products as $product ) {
$packages = [];
foreach ( $product->packageId as $package ) {
$packages[] = [
'package_id' => $package['id'],
];
}
$data[] = [
'id' => $product->id,
'packages ' => $packages,
]
}
EDIT:
Please try again with a revised version of the code you provide below.
foreach ( $products as $product ) {
$sums = 0;
$packages = [];
foreach ( $product->packageId as $package ) {
// Get the total existing inventory
$pckInvSum = $package->pckInventories
->where( 'expiry_date', '<', Carbon::today() )
->where( 'type', 'existing' )->sum( 'amount' );
// Get the total virtual inventory
$pckInvVirtual = $package->pckInventories->where( 'type', 'virtual' )->sum( 'amount' );
// create new array packages to add it to the main json
$packages[] = [
'package_id' => $package['id'],
'package_price' => $package['price'],
'unit_count' => $package['unit_count'],
'existing' => $pckInvSum,
'virtual' => $pckInvVirtual
];
$sums += $package->pckInventories->sum( 'amount' );
}
$data[] = [
'id' => $product->id,
'product_category_id' => $product->product_category_id,
'child_category_id' => $product->child_category_id,
'child_category_two_id' => $product->child_category_two_id,
'child_category_three_id' => $product->child_category_three_id,
'supplier_id' => $product->supplier_id,
'supplier_name' => $product->supplier->contact_name,
'option_category_id' => $product->option_category_id,
'tax_id' => $product->tax_id,
'barcode' => $product->barcode,
'low_price' => $product->low_price,
'image' => $product->image,
'cost' => $product->cost,
'name_ar' => $product->translations[0]->name,
'name_en' => $product->translations[1]->name,
'details_ar' => $product->translations[0]->details,
'details_en' => $product->translations[1]->details,
'sumInv' => $sums,
'campaign' => [
'id' => $product->campaign[0]->id,
'product_id' => $product->campaign[0]->product_id,
'price' => $product->campaign[0]->price,
'purchasesLimits' => $product->campaign[0]->purchasesLimits,
],
'packages' => $packages,
];
}
I am new to this stuff. I just inherited this olde system! I managed to get Solr running, and am trying to execute some old code that rebuilds the Solr data. The client ping is failing and I don't understand why.
Here is the code that is trying to initiate a re-index
// these are correct, now Solarium is falling over
// with a 404. pile of junk
print(SOLR_SERVER_HOSTNAME . "\n");
print(SOLR_SERVER_PORT . "\n");
print(SOLR_SERVER_CORE . "\n");
$options = array(
'adapteroptions' => array(
'host' => SOLR_SERVER_HOSTNAME,
'port' => SOLR_SERVER_PORT,
'core' => SOLR_SERVER_CORE,
'timeout' => 60
)
);
}
try {
// Ping the Solr server to check its availability
// create a new client. This seems to work
$this->client = new Solarium_Client($options);
if ($this->client) {
print("Solarium returned something \n");
print_r($this->client);
print("\n");
} else {
echo 'Solarium screwed the pooch';
}
// and create a ping whatever that means
// this also seems to work
$ping = $this->client->createPing();
if ($ping) {
print("ping creation worked \n");
print_r($ping);
} else {
print("ping creation failed \n");
}
// this always fails and terminate the
// program run
$this->client->ping($ping);
} catch (Solarium_Exception $e) {
print("exeption from ping request \n");
throw $e;
}
print("about to reset \n");
// Reset all filters and queries and process request params if requested
$this->reset($request);
}
The Solr admin screen is up. I have an empty collection1..
Here is the output from the trace I stuck in here
1/tmp/reindex.lock
15/01/18 17:38:54 [INFO] Index started
Index started
localhost
9999
collection1
Solarium returned something
Solarium_Client Object
(
[_options:protected] => Array
(
[adapter] => Solarium_Client_Adapter_Http
[adapteroptions] => Array
(
[host] => localhost
[port] => 9999
[core] => collection1
[path] => /solr/
[timeout] => 60
)
)
[_queryTypes:protected] => Array
(
[select] => Array
(
[query] => Solarium_Query_Select
[requestbuilder] => Solarium_Client_RequestBuilder_Select
[responseparser] => Solarium_Client_ResponseParser_Select
)
[update] => Array
(
[query] => Solarium_Query_Update
[requestbuilder] => Solarium_Client_RequestBuilder_Update
[responseparser] => Solarium_Client_ResponseParser_Update
)
[ping] => Array
(
[query] => Solarium_Query_Ping
[requestbuilder] => Solarium_Client_RequestBuilder_Ping
[responseparser] => Solarium_Client_ResponseParser_Ping
)
[mlt] => Array
(
[query] => Solarium_Query_MoreLikeThis
[requestbuilder] => Solarium_Client_RequestBuilder_MoreLikeThis
[responseparser] => Solarium_Client_ResponseParser_MoreLikeThis
)
[analysis-document] => Array
(
[query] => Solarium_Query_Analysis_Document
[requestbuilder] => Solarium_Client_RequestBuilder_Analysis_Document
[responseparser] => Solarium_Client_ResponseParser_Analysis_Document
)
[analysis-field] => Array
(
[query] => Solarium_Query_Analysis_Field
[requestbuilder] => Solarium_Client_RequestBuilder_Analysis_Field
[responseparser] => Solarium_Client_ResponseParser_Analysis_Field
)
[terms] => Array
(
[query] => Solarium_Query_Terms
[requestbuilder] => Solarium_Client_RequestBuilder_Terms
[responseparser] => Solarium_Client_ResponseParser_Terms
)
[suggester] => Array
(
[query] => Solarium_Query_Suggester
[requestbuilder] => Solarium_Client_RequestBuilder_Suggester
[responseparser] => Solarium_Client_ResponseParser_Suggester
)
)
[_pluginTypes:protected] => Array
(
[loadbalancer] => Solarium_Plugin_Loadbalancer
[postbigrequest] => Solarium_Plugin_PostBigRequest
[customizerequest] => Solarium_Plugin_CustomizeRequest
[parallelexecution] => Solarium_Plugin_ParallelExecution
[bufferedadd] => Solarium_Plugin_BufferedAdd
[prefetchiterator] => Solarium_Plugin_PrefetchIterator
)
[_pluginInstances:protected] => Array
(
)
[_adapter:protected] =>
[_requestBuilders:protected] =>
)
ping creation worked
Solarium_Query_Ping Object
(
[_options:protected] => Array
(
[resultclass] => Solarium_Result_Ping
[handler] => admin/ping
)
[_helper:protected] =>
[_params:protected] => Array
(
)
)
exeption from ping request
Failed to initialise Solr client:
Solr HTTP error: Not Found (404)
Failed to initialise Solr client: Solr HTTP error: Not Found (404)
Any hints? It's the first time I have seen this stuff.
Cheers,
Mark.
Fixed. The core name was getting flattened in another bit of code. Two constants for the same property. Two different values! – Addinall 22 secs
I'm currently using DB-Transaction and it throws Lexical variable error
attached here is my code:
DB::transaction(function ($request) use ($request) {
$salesman = new Salesman([
'operation_id' => $request->get('operation_id'),
'warehouse_id' => $request->get('warehouse_id'),
'salesman_name' => $request->get('salesman_name'),
'address' => $request->get('address'),
'contact_number' => $request->get('contact_number'),
'email_address' => $request->get('email_address'),
'area_id' => 'pending',
]);
$salesman->save();
});
return view('salesman.index');
}
It is working now after I remove the $request parameter in function
DB::transaction(function () use ($request) {
$salesman = new Salesman([
'operation_id' => $request->get('operation_id'),
'warehouse_id' => $request->get('warehouse_id'),
'salesman_name' => $request->get('salesman_name'),
'address' => $request->get('address'),
'contact_number' => $request->get('contact_number'),
'email_address' => $request->get('email_address'),
'area_id' => 'pending',
]);
$salesman->save();
});
return view('salesman.index');
}