Convert an array of array onto Collection Laravel - laravel

I have an array of array which results from several sql requests.
First I make a sql request in a foreach in order to have all the datas i need
foreach ($users as $user) {
// Two different Eloquent requests
$todo = User::select().....where('users.id' = $id);
$done = User::select().....where('users.id' = $id);
// I have operation on Collection that work fine ...
$totalTimes = $todo->toBase()->sum('dureeformation') ;
$spendTimes = $done->toBase()->sum('dureeformation') ;
$remainingTimes = $totalTimes - $spendTimes;
$all[] = ['user_id' => $id, 'totalTime' => $totalTimes, 'spendTime' => $spendTimes,'remainingTime' => $remainingTimes ];
}
My issue is the following... Outside the foreach i display the values and i have this array of array ...
array:16 [▼
0 => array:4 [▼
"user_id" => 1
"totalTime" => 465
"spendTime" => 0
"remainingTime" => 465
]
1 => array:4 [▼
"user_id" => 3
"totalTime" => 375
"spendTime" => 0
"remainingTime" => 375
]
I would need to have a Collection instead ... I tried to make $all = Collect(....) but i doesn't give me the expected result.
I need a collection because i have to create a Collection with this created collection and another one from another request.
Concerning this part i already had this case and i can solve it.
Thanks for your help

try this helper function :
$collection = collect($all);
This function will convert your array to collection.

Related

Expected type 'iterable|object'. Found 'string'

I am trying to iterate a set of array values returned from my laravel view in a multi-select dropdown field. When I submit my form, below is the data sent to my livewire component.
^ array:4 [▼
"scheduled_date" => "2022-09-30 12:00"
"recipient" => "2"
"classrooms" => array:4 [▼
0 => "2"
1 => "3"
2 => "4"
3 => "5"
]
"smsdetail" => "Testing for a particular Class"
]
I need to iterate data in classrooms array and save them as different records with the rest of the top-level data to db which is not the problem. My struggle is to iterate and pick values for classrooms.
The below set of codes gives me the error Expected type 'iterable|object'. Found 'string'. I need help.
case ('2'):
$recipients = $this->state['classrooms'];
foreach ($recipients as $key => $recipient)
{
dd($recipient);
}
case ('2'):
$recipients = $this->state['classrooms'];
foreach ($recipients as $recipient)
{
dd($recipient);
}

How to foreach in store method in laravel?

I have the following array in dd($request->all())
"question_id" => array:2 [▼
0 => "1"
1 => "2"
]
"answers" => array:2 [▼
0 => "1 year"
1 => "yes"
]
I need to loop this array to store in this table
which is this request came from dynamic form i create.
I've tried this method
$data = $request->all();
$questions = $data['question_id'];
$answers = $data['answers'];
$dataanswer = [];
foreach($answers as $answer){
$dataanswer[] = [
'question_id' => $questions,
'answer' => $answers
];
}
Answers::insert($dataanswer);
but it says Array to string conversion, please help me.
You can use PHP's array_combine() function :
$data = $request->all();
$questions = $data['question_id'];
$answers = $data['answers'];
Answers::insert(array_combine($questions, $answers));
Here is a demo
If your questions and answers in right order (e.g. 1 => '1 year' and 2 => 'yes), than:
$data = collect($request->input('question_id'))
->combine($request->input('answers'));
Model::insert($data);
i end up using this method, and works perfectly
thanks for the answers guys stay healthy
$count = count($request->input('question_id'));
for($i = 0 ;$i < $count ; $i++){
$questions = $data['question_id'][$i];
$answers = $data['answers'][$i];
Answers::create([
'application_id' => $applicant['id'],
'question_id' => $questions,
'answer' => $answers
]);
}

Apply reduce method for all properties of an object

I have an object in Laravel that represent a monthly report.
0 => array:20 [▼
"id" => 43
"operation_id" => 1
"meter_id" => 3
"period" => "monthly"
"total_conso" => "103.42"
"total_autoconso" => "59.47"
"total_grid" => "43.95"
"bill" => "31.95"
"grid_fee" => "26.97"
"solar_turpe_tax_fee" => "4.99"
"savings" => "4.41"
"total_prod" => null
"total_surplus" => null
"autoconso_rate" => "57.5"
"autoprod_rate" => null
"surplus_rate" => null
"date" => "2019-08-24T00:00:00.000000Z"
"created_at" => "2019-08-24T00:00:00.000000Z"
"updated_at" => "2020-10-01T15:03:38.000000Z"
I have a array with 12 objects of these, one per month.
I am calculating the yearly report values, and I have to sum all 12 month for each field.
I can do it with reduce field by field with:
$totalConso = $reports->reduce(function ($sum, $report) {
return $sum + $report->total_conso;
}, 0);
What I am looking for is a way to do it for all fields. Is it possible ? It would allow me not to duplicate 10 times the same reduce function
Thanks !
You could do something like this:
[$totalConso, $totalAutoConso] = collect(['total_conso', 'total_autoconso'])->map(fn ($property) => $reports->sum($property));
If you would prefer an array with each total:
$totals = collect(['total_conso', 'total_autoconso'])->mapWithKeys(fn ($property) => [$property => $reports->sum($property)]);
This would give you a collection with all the totals.
If you don't like hardcoding the list of total_* attributes, you can get them dynamically from the list of fillable attributes of your model (this assumes you use the fillable property):
$totals = collect(Report::make()->fillable)
->filter(fn ($property) => strpos($property, 'total_') === 0)
->mapWithKeys(fn ($property) => [$property => $reports->sum($property)]);
Demo: https://laravelplayground.com/#/snippets/ec3c662f-0ab9-4de8-8422-7bed2f054677
Use the collect helper and sum method:
$total = collect($reports)->sum('total_conso');

Laravel parameterBag as array issues when inserting

I am trying to insert mass data but i get this error when i iterate through the request:
Symfony\Component\Debug\Exception\FatalThrowableError Cannot use
object of type Symfony\Component\HttpFoundation\ParameterBag as array
Request example:
request: Symfony\Component\HttpFoundation\ParameterBag {#52 ▼
#parameters: array:4 [▼
"_token" => "Z1sF2K5LHU1bsQ4l3JRaOLCTQDmJ47qakigmrfI5"
"name" => "Rousaddasd 1"
"secsaddsans" => array:1 [▼
"secsdfs1" => array:2 [▼
"name" => "Sectdfs 1"
]
]
"submit" => "Submit"
]
}
Loop to go through the request and insert:
$abc = new abc;
$abc->create(['user_id' => 1, 'name' => $request->name, 'description' => 'test description']);
foreach($request as $item){
$asd = new asd;
$asd->name = $item['name'];
$asd->description = 'test description';
$abc->asds()->create([$asd]);
}
Im adding some data "inline" because i didnt handle them in the form yet, thats why the added duration and duration_unit for example.
You can use $request as array like this:
$request = $request->all();
And loop like:
foreach($request['sections'] as $item) {
....
foreach($item['exercises'] as $item2) {
....
}
}

Process Collection through Map function

I get a Collection from a Query in Laravel.
Actually, I'm processing collection like that:
foreach ($cts as $ct) {
$array[$ct->id] = $ct->category->name;
}
It outputs this:
array:2 [▼
1158 => "Junior por Equipo"
1160 => "Varonil por Equipo"
]
Now, I would like to user map() function over muy collection as I like it better:
MyModel::get()
->get()
->map(function ($item, $value){
return [ $item->id => $item->category->name ];
})->toArray();
But now, I get :
array:2 [▼
0 => array:1 [▼
1158 => "Junior por Equipo"
]
1 => array:1 [▼
1160 => "Varonil por Equipo"
]
]
How should I do to output it like the first case?
You don't have to map the collection, just use MyModel::lists('name', 'id' ) ;
There is a collection method for that. pluck() and eloquent lists()
no its preferred to use pluck for getting some columns only. previously lists() was used.
see https://laravel.com/docs/5.3/collections#method-pluck
as the document says
The pluck method retrieves all of the values for a given key/keys only
so it would be something like this.
Model::get()->pluck('name','id);
Than you can do toArray() on the result if you want to get an array instead of a collection.

Resources