Laravel API response conversion into collection - php

I'm playing with API responses for a while and I can't convert them into Laravel collection format.
My response after $users = json_decode($users, true); is something like that:
array:2 [▼
"#odata.context" => "https://URL/Something.svc/$metadata#Something"
"value" => array:190 [▼
0 => array:18 [▶]
1 => array:18 [▶]
2 => array:18 [▶]
3 => array:18 [▶]
4 => array:18 [▶]
5 => array:18 [▶]
6 => array:18 [▶]
7 => array:18 [▶]
I need to convert it into Laravel collection so instead of original json_decode I have to use:
$users = collect(array_values(json_decode($users, true))[1]);
It works, but I felt that this is not the right way to do that? Also, I have to use [1] at the end. What's if the array is empty and [1] does not exist? Do I need to validate if it exists or if there is a proper way to deal with this conversion?

After decoding the data you will have an associative array where you can access the data inside the 'value' array directly using $users['value'], so there is not need to use the array_values function.
$users = json_decode($users, true);
if (isset($users['value'])) {
$usersCollection = collect($users['value']);
}
I guess something like this should work fine.

Related

How to save multiple array input data in Database in Laravel PHP

Hello Geeks i am stuck here. I am beginner and want to know how to save and update array data in database.
this is laravel form requested data
I want to save data like this :
mysql database
here is my form request, i want to save data in mysql database, with new row :
"_token" => "FoyoYvFXmNAggbQuMq6PN243QS43MkY99Nq3UAni"
"description" => array:2 [▼
0 => "<h3>Shared Hosting Plan</h3>"
1 => "<h3>Cloud Hosting Plan</h3>"
]
"site_id" => array:2 [▼
0 => "5361"
1 => "5361"
]
"category_id" => array:2 [▼
0 => "1"
1 => "3"
]
"field_1" => array:2 [▶]
"field_2" => array:2 [▶]
"field_3" => array:2 [▶]
"field_4" => array:2 [▶]
"field_5" => array:1 [▶]
"price" => array:2 [▶]
"update_plan" => "Save Plans"
]```
Try like this
$save_data=[];
foreach($data['description'] as $key=>$desc){
$save_data[]=[
'description'=>$desc,
'site_id'=>$data['site_id'][$key],
'category_id'=>$data['category_id'][$key],
'feature_field_1'=>$data['field_1'][$key],
'feature_field_2'=>$data['field_2'][$key],
'feature_field_3'=>$data['field_3'][$key],
'feature_field_4'=>$data['field_4'][$key],
'feature_field_5'=>$data['field_5'][$key],
'price'=>$data['price'][$key]
]
}
\DB::table('table')->insert($save_data);
You can insert like this
Eloquent approach
Model::insert($data);
Query Builder approach
DB::table('table')->insert($data);

How to display pagination links in a blade on Laravel 8?

I need to add pagination, but it seems complicated in my case, because I get data from database with paginate, but then I modify this data and when I call links() method on the blade, I get the following exception
Method Illuminate\Support\Collection::links does not exist.
My code in the Controller method:
$transactionsByLastMonth = Transaction::where('created_at', '>=', Carbon::now()->subDays(30)->toDateTimeString())
->where('user_id', Auth::user()->id)
->with(['user', 'propertyFrom', 'propertyTo', 'paddockFrom', 'paddockTo', 'cattleTypeFrom', 'cattleTypeTo'])
->paginate(10);
$transactionsByDays = collect(TransactionResource::collection($transactionsByLastMonth))
->sortByDesc('created_at')
->groupBy(function($date) {
return Carbon::parse($date['created_at'])->format('d');
});
return view('user.reports.index', compact('transactionsByDays'));
Yes, a pagination limits my data to 10 rows, but due to I'm grouping data by days, my collection modifies itself and I can't use $transactionsByDays->links() method to show pagination.
If see dd($transactionsByDays) , it looks like:
Illuminate\Support\Collection {#1381 ▼
#items: array:3 [▼
"01" => Illuminate\Support\Collection {#1019 ▼
#items: array:7 [▼
0 => array:16 [▶]
1 => array:16 [▶]
2 => array:16 [▶]
3 => array:16 [▶]
4 => array:16 [▶]
5 => array:16 [▶]
6 => array:16 [▶]
]
}
31 => Illuminate\Support\Collection {#1386 ▼
#items: array:2 [▼
0 => array:16 [▶]
1 => array:16 [▶]
]
}
30 => Illuminate\Support\Collection {#1384 ▼
#items: array:1 [▼
0 => array:16 [▶]
]
}
]
}
Therefore I need to paginate all arrays together which inside "01", 31, 30...
How can I do it?
Maybe rewrite code above in the controller somehow?
The main aim is that I need to group data to every day according to my json-resource class.
Any ideas?
I've found a solution gyus. I had to pass also a variable transactionsByLastMonth and use links() method over this.
In the meantime I use foreach on the my blade file over transactionsByDays variable. It's correctly works together cause it uses the same data from database, just in the first case its not filtered and not grouped and in the second one it is.
return view('user.reports.index', compact('transactionsByLastMonth', 'transactionsByDays'));

How to update a nested value within a nested Laravel collection

I have a deployments Laravel Collection like this:
Illuminate\Support\Collection {#415 ▼
#items: array:5 [▼
0 => array:7 [▼
"id" => 31
"status" => "active"
"name" => "Deployment 1"
"spots" => array:4 [▼
0 => array:2 [▼
"id" => 33
"status" => "active" <-- Want to change this
]
1 => array:2 [▶]
2 => array:2 [▶]
3 => array:2 [▶]
]
"data" => array:3 [▶]
]
1 => array:7 [▶]
2 => array:7 [▶]
3 => array:7 [▶]
4 => array:7 [▶]
]
}
I want to update the nested status value to inactive. I have used the Laravel map function, but it only seems to work on collections that have one nesting level. So this...
$this->deployments->map(function ($deployment) {
$deployment['spots'][0]['status'] = 'inactive';
});
dd($this->deployments);
...leaves $this->deployments untouched.
Also tried using nested map functions obtaining a Call to a member function map() on array exception on second level as second and next nesting levels are considered arrays...
Any thoughts?
Thanks in advance.
With the map method, you are almost there. You will have to return the change made in $deployment and do an ->all() at the end to update the collection with the modified values.
For updating a single spot:
$deployments = $deployments->map(function($deployment){
$deployment['spots'][0]['status'] = 'inactive';
return $deployment;
})->all();
For updating all spots:
$deployments = $deployments->map(function($deployment){
foreach($deployment['spots'] as &$spot){
$spot['status'] = 'inactive';
}
return $deployment;
})->all();
For anyone researching this, a more elegant solution might be:
For updating a single spot:
$data = $deployments->all();
$deployments = data_set($data, 'spots.0.status', 'inactive');
For updating all spots:
$data = $deployments->all();
$deployments = data_set($data, 'spots.*.status', 'inactive');

Yaml nested arrays in php

Trying to convert nested php array
$ar:3 [▼
"sotr" => array:5 [▼
0 => {#190 ▼
+"sId": "1"
+"sFIO": "Родион Романович Мишин"
+"sSalary": "7477.59"
}
1 => {#192 ▶}
2 => {#193 ▶}
3 => {#194 ▶}
4 => {#195 ▶}
]
"ticket" => array:5 [▶]
"task" => array:4 [▶]
]
into YAML string by using Symfony\Component\Yaml\Yaml in Laravel. So, when I'm using
$data = Yaml::dump($ar);
I see empty array like this:
sotr:\n
- null\n
- null\n
- null\n
- null\n
- null\n
How I can fix this?
solve it! Probably this solution not so smart, but it works.
Convert array into JSON string:
$data = json_decode(json_encode($ar), true);
Then using Symfony\Component\Yaml\Dumper class
$dumper = new Dumper();
$yaml = $dumper->dump($data);
And here the YAML formatted string:
sotr:
-
sId: '1'
sFIO: 'Родион Романович Мишин'
sSalary: '7477.59'

Laravel use decoded JSON data as PHP Object

I want to use decoded JSON data as php objects to be able to used as follows:
return $data->title
however im running into a few errors. I am able to connect to the remote API url and get the requested data.
$api = 'https://remote.api.url/dataset/list';
$json = file_get_contents($api);
$data = json_decode($json, true);
dd($data);
When i die and dump the data i see the following:
array:1 [▼
"data" => array:5 [▼
0 => array:5 [▼
"id" => "qk4GtMb8"
"title" => "SSA's palliative care has an mHealth deficit "
"image" => "http://gstatic.acfee.org/akamaihd/i/52fdb957187"
"published_at" => "2016-06-10 08:05:00"
"created_at" => array:3 [▼
"date" => "2016-06-07 05:48:34.000000"
"timezone_type" => 3
"timezone" => "UTC"
]
]
1 => array:5 [▶]
2 => array:5 [▶]
3 => array:5 [▶]
4 => array:5 [▶]
]
]
But i am unable to use the recieved data in object form. return $data->title;
i am pretty new to JSON any help would be appreciated.
Thanks in advance.
The second parameter of json_decode (which in your case is true) converts the objects to array. From official PHP docs: When TRUE, returned objects will be converted into associative arrays. So if you remove it you should be ok.

Categories