How to sort/order a model's fields? - php

I do $users = User::all(); This gives me a collection of User objects, where each object has fields something like:
[
{
"id":10,
"age":10,
"name":"John",
"bank_no":5454
},
{
"id":20,
"age":10,
"name":"Jane",
"bank_no":457
}
]
I want each User objects keys to be ordered alphabetically,
For ex:
[
{
"age":10,
"bank_no":5454
"id":10,
"name":"John"
},
{
"age":10,
"bank_no":457
"id":20,
"name":"Jane"
}
]
Now I know that this order comes the order in which the fields are defined in the migration file. But, changing the migration is not an option for me.
How can I do this efficiently?

Sorting by keys you can to do this :
$users = User::all();
foreach ($users as $key => $value) {
ksort($key);
}
Try this.

here try this, I'm not sure if this going to be the efficient solutions for a very long list of users but it should work regardless.
$json = '[
{
"id":10,
"age":10,
"name":"John",
"bank_no":5454
},
{
"id":20,
"age":10,
"name":"Jane",
"bank_no":457
}
]';
$arr = json_decode($json, true);
$res = [];
foreach($arr as $arrObj){
ksort($arrObj);
$res[] = $arrObj;
}
print_r($res);
Laravel sort function on collection see documentation here
$collection = collect([
'id' => 22345,
'first' => 'John',
'last' => 'Doe',
]);
$sorted = $collection->sortKeys();
$sorted->all();

Related

How do I work with a collection that is a child of a collection in Laravel 5.7?

How can I return the child collection of a collection in Laravel 5.7? I have a Laravel collection that itself contains a collection. When I return the parent collection through my api, there is clearly a "children" object, but when I try to return the "children" object it is null.
Relevant collection code:
$item = [
'id' => $this->id,
...
$this->mergeWhen($this->type === Item::[type], [
...
'children' => [type]::collection($this->[prop])
]),
...
return $item;
];
Relevant api controller code:
$itemsQuery = $[parent_type]->items()->topLevel()->withAll()->ordered()->get();
$items = [type]::collection($itemsQuery);
$return_array = [];
foreach ($items as $item)
{
array_push($return_array, $item);
}
return $return_array;
This returns what I would expect.
"data": {
"id": [guid],
...
"children": [
{
"id": [guid],
...
}
]
}
but when I change it to
$itemsQuery = $[parent_type]->items()->topLevel()->withAll()->ordered()->get();
$items = [type]::collection($itemsQuery);
$return_array = [];
foreach ($items as $item)
{
array_push($return_array, $item->children);
}
return $return_array;
I get
"data": null
Try this :
...
$return_array = collect();
foreach ($items as $item)
{
$return_array->push($item->children);
}
return $return_array->toArray();
There is a collect() helper, not sure if that will help you out, but you can convert a basic array to a collection that way.

How to show array in Json with Fractal?

I want to save REST API data with array to database, its work, all value save to the table, but i still get error when i want to view the result in json.
Here is my error
"message": "Argument 1 passed to App\\Transformers\\NewLoanOfferTransformer::transform() must be an instance of App\\Model\\AntiAttrition, array given, called in /home/insko23/testing.insko.my/vendor/league/fractal/src/Scope.php on line 338",
My Controller
public function new_loan_offer(Request $request, AntiAttrition $antiattrition)
{
$new = array_map(null, $request->mo_id, $request->id_clrt,$request->TaskID,$request->ACID,$request->CustIDNo);
foreach($new as $new) {
$request = new AntiAttrition;
$request->mo_id = $new[0];
$request->id_clrt = $new[1];
$request->TaskID = $new[2];
$request->ACID = $new[3];
$request->CustIDNo = $new[4];
$request->save();
}
$response = fractal()
->item($new)
->transformWith(new NewLoanOfferTransformer)
->toArray();
return response()->json($response,201);
}
My App\Transformer
<?php
namespace App\Transformers;
use App\Model\AntiAttrition;
use App\Model\SettlementInfo;
use League\Fractal\TransformerAbstract;
class NewLoanOfferTransformer extends TransformerAbstract
{
public function transform (AntiAttrition $antiattrition)
{
return[
'id' => $antiattrition->id,
'mo_id'=> $antiattrition->mo_id,
'assign_by'=> $antiattrition->assigned_by,
'id_clrt' => $antiattrition->id_clrt,
'TaskID'=> $antiattrition->TaskID,
'ACID'=> $antiattrition->ACID,
'CustIDNo'=> $antiattrition->CustIDNo
];
}
}
I want to show the result in json, like below
{
"data": [
{
"mo_id": "123",
"id_clrt": "10000000049",
"ACID": "123",
.....
},
{
"mo_id": "1234",
"id_clrt": "10000000045",
"ACID": "1235",
.....
},
{
"mo_id": "124",
"id_clrt": "10000000044",
"ACID": "1245",
.....
},
],
}
Please help me to solve this problem
In the foreach loop, avoid using same name for array and elements of the array you are iterating over, you can rename foreach($new as $new) to foreach($newArray as $new), or something meaningful with your code logic. Also rather than using $new[0] use $new['mo_id'] for referring to the key of the array

How to get all records in if conditions using Laravel

I have two request parameters in array:
{
"users": [1,2,3],
"groups": [1,2]
}
I want to get records of users against id 1,2,4 and groups against id 1,2 I can fetch records of users but I am unable to fetch records of groups.
Here is my code:
public function isGroupUser(Request $request)
{
$usersDetail = $request->input('users', []);
$groupsDetails = $request->input('groups', []);
if($usersDetail)
{
$users = DB::table('users')
->join('user_basic_info','users.id','=','user_basic_info.user_id')
->select('users.id','user_basic_info.first_name')
->whereIn('users.id',$usersDetail)->get();
$resultArray = ['users' => $users];
return \Illuminate\Support\Facades\Response::json($resultArray, 200);
}
elseif ($groupsDetails)
{
$groups = DB::table('group')
->select('group.id','group.name')
->whereIn('group.id',$groupsDetails)->get();
$resultArray = ['groups' => $groups];
return \Illuminate\Support\Facades\Response::json($resultArray, 200);
}
}
I can get the records of users but not getting groups. Where am I wrong?
Currently my JSON response:
{
"users": [
{
"id": 1,
"first_name": "Admin"
},
{
"id": 2,
"first_name": "Admin"
},
{
"id": 3,
"first_name": "Admin"
}
]
}
But not getting the groups.
You got some problems
You are replacing resultArray when you are trying to assign groups to it,
You are writing elseif condition which suggest, only one of two condition will always satisfy
Change these two lines
$resultArray['users'] = $users; // here result array will have key users
$resultArray['groups'] = $groups; // here result array will have key groups
elseif ($groupsDetails) replace this with if($groupsDetails)
In above case, its pushing data into array. In your case its replacing array.
It should work.
change your code like below,
in your code only one part (either if or elseif) works
$usersDetail = $request->input('users', []);
$groupsDetails = $request->input('groups', []);
$resultArray = []; // an empty array to store your results
if($usersDetail)
{
$users = DB::table('users')
->join('user_basic_info','users.id','=','user_basic_info.user_id')
->select('users.id','user_basic_info.first_name')
->whereIn('users.id',$usersDetail)->get();
$resultArray['users'] = $users;
}
if ($groupsDetails)
{
$groups = DB::table('group')
->select('group.id','group.name')
->whereIn('group.id',$groupsDetails)->get();
$resultArray['groups'] = $groups;
}
return \Illuminate\Support\Facades\Response::json($resultArray, 200);
just remove first return. because if in request have user then when got to return and then get out from if anad not get to second return.
edited: #Shobi answered well

PHP using json_encode, must output the specific data

I'm currently stuck at this scenario, now the other developer wants to output the API structure as seen on attached image.
json_required_format
But I tried as far as I can but I only got these result:
"all_projects": {
"TEST TOWNHOMES": {
"unit_types": [
{
"unit": "TOWNHOUSE 44.00"
}
]
},
"TEST HOMES": {
"unit_types": [
{
"unit": "DUPLEX WITH OUT GARAGE 44.50"
}
]
},
"TEST HOMES II": {
"unit_types": [
{
"unit": "DUPLEX WITH OUT GARAGE 44.50"
}
]
},
"TEST VILLAGE": {
"unit_types": [
{
"unit": "TOWNHOUSE 44.00"
},
{
"unit": "DUPLEX WITHOUT GARAGE 52.30"
}
]
}
I am using MVC framework,
This is my model looks like:
public function all_south_projects()
{
$this->db->distinct();
return $this->db->select('Project as project_name')->from('lots')
->where('available','YES')
->get()->result();
}
public function get_unit_types($projName)
{
$this->db->distinct();
return $this->db->select('UnitType as unit')->from('lots')
->where('Project',$projName)
->where('Available','YES')
->get()->result();
}
And then my controller is:
$resp = $this->MyModel->all_south_projects();
$test_array = array();
foreach ($resp as $value) {
$units = $this->MyModel->get_unit_types($value->project_name);
$allunits = array("unit_types"=>$units);
$allunits = (object) $allunits;
$test_array[$value->project_name] = $allunits;
}
//var_dump($test_array);
$stat = 200;
$message = 'Successfully fetched.';
if(empty($test_array)){
$empty=json_decode('{}');
json_output2($stat,'all_projects',$message,$empty);
}else{
json_output2($stat,'all_projects',$message,$test_array);
}
json_output2 is on my helper to customize json format:
Here is my code:
function json_output2($statusHeader,$responseName,$message,$response)
{
$ci =& get_instance();
$ci->output->set_content_type('application/json');
$ci->output->set_status_header($statusHeader);
$ci->output->set_output(json_encode(array('status' =>
$statusHeader,'message' => $message,$responseName =>$response)));
}
NOTE: Scenario is:
The API must give all the projects having available units,
if the project is available, then it needs to get its corresponding available units to view. I know I can make another API call but this time, we need to improve the UX.
Can someone enlighten me to get through this? Thank you!
Change this part :
foreach ($resp as $value) {
$units = $this->MyModel->get_unit_types($value->project_name);
$allunits = array("unit_types"=>$units);
$allunits = (object) $allunits;
$test_array[$value->project_name] = $allunits;
}
To :
foreach ($resp as $value) {
$units = $this->MyModel->get_unit_types($value->project_name);
$test_array[] = [
"project_name" => $value->project_name,
"unit_types" => $units
];
}
You don't have to cast your associative array to object like you did there : $allunits = (object) $allunits; because an associative array will always be serialized as a JSON object (associative arrays do not exist in JSON).

merge Array of objects into array with unique object

I have a array of various object, but I need turn this objects into unique object. Below I share my code.
$result = [];
$idiomas = Idioma::all()->toArray();
foreach ($idiomas as $lang) {
$result[] = [
$lang['palavra_chave'] => $lang[$id]
];
}
return response()->json($result);
reponse
[
{ "INICIAL": "Inicial"},{ "RELATORIOS": "Relatórios"},{ "FUNCIONARIO": "Funcionário"},{ "DATA": "Data"},{ "ANEXAR_IMAGEM": "Anexar imagem"},{ "DISCIPLINA": "Disciplina"}
]
But I need transform this objects into one, like this
[
{
"INICIAL": "Inicial",
"RELATORIOS": "Relatórios",
"FUNCIONARIO": "Funcionário",
"DATA": "Data",
"ANEXAR_IMAGEM": "Anexar imagem",
"DISCIPLINA": "Disciplina"
}
]
anyone can help me?
$idiomas = Idioma::all()->toArray();
if (count($idiomas)) {
//$result = new stdClass; # wouldn't work without base namespace
$result = new \stdClass;
foreach ($idiomas as $lang) {
$result->{$lang['palavra_chave']} = $lang[$id];
}
return response()->json([$result]);
}
// otherwise
Edit: #Tpojka's answer definitely looks more appropriate. Use the following one only if you can't change the way you retrieve data initially (I'm not familiar enough with Laravel).
The following should work:
// Take your initial JSON
$input = <<<JSON
[
{ "INICIAL": "Inicial"},{ "RELATORIOS": "Relatórios"},{ "FUNCIONARIO": "Funcionário"},{ "DATA": "Data"},{ "ANEXAR_IMAGEM": "Anexar imagem"},{ "DISCIPLINA": "Disciplina"}
]
JSON;
// Transform it into a PHP array
$input_as_array = json_decode($input);
// Reduce it into an associative array
$associative_array = array_reduce($input_as_array, function($associative_array, $item) {
return $associative_array += (array)$item;
}, []);
// Encode it back into JSON, as an array
$result = json_encode([$associative_array], JSON_PRETTY_PRINT);

Categories