How retrieve element from collection by name? - laravel

First, I create collection from array:
$bank_center = collect(array("amount" => null, "mfo" => null, "name" => null));
Then I try to get value by key:
dd($bank_center->name);
Dump is:
Collection {#562 ▼
#items: array:3 [▼
"amount" => null
"mfo" => null
"name" => null
]
}

In your particular case, the following would just work:
$bank_center['name'];
I am not sure why you want to wrap it as an object, but if you still wish to do it, I'd recommend you take a look at Fluent.
$bank_center = new \Illuminate\Support\Fluent(array("amount" => 'test', "mfo" => 'test2', "name" => 'test3'));
dd($bank_center->name); // test3

You should use square brackets to access item from such collection:
$bank_center['name']

To retrieve element by name from collection you can use get method, it returns the item at a given key. If the key does not exist, null is returned:
$collection = collect(['name' => 'bruno', 'framework' => 'laravel']);
$value = $collection->get('name');
// bruno

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);
}

Get all names from array and pluck them together Laravel 8

I got an array in witch are nested arrays and I want to get names from those nested arrays and display them together. I have been searching a lot and can't figure out how. I am using laravel 8.
array:2 [▼
"5dd48809b061f7a3828cb5267794ce39" => array:10 [▼
"name" => "test"
]
"7d504e7f837b2f9bb03dca5f9c8da9f5" => array:10 [▼
"name" => "test2"
]
]
You can do that in basic PHP with the array_column function.
$names = array_column($array, 'name');
The above example would output:
array(
[0] => 'test',
[1] => 'test2',
);
You can also keep the ID as key, if it exists within the nested array:
$names = array_column($array, 'name', 'id');
The above example would e.g. output:
array(
[1515] => 'test',
[2522] => 'test2',
);
There are more examples in the documentation:
https://www.php.net/manual/en/function.array-column.php

Laravel FirstOrCreate function with null value converts to string

I send a null value for search field, and it converts to string.
using laravel 8. php 7.4
$notification = Notification::firstOrCreate([
'resource' => $notif['resource'],
'topic' => $notif['topic'],
'response' => null
], [some other values]);
returns
#attributes: array:12 [
"resource" => "/item/55359"
"topic" => "item"
"response" => "null" --> like string and not null value
"status_id" => "Pending"
"attempts" => 0
]
thanks
it was a model problem...
the response field saves a json string.. and it was converting the null value to json string.
that was the problem.
i have add this line before
if (is_null($value)) $this->attributes['response'] = $value;
thanks all

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');

Array of selected options in Form::select?

I have an array that contains ids of selected options in select list (html).
In Laravel it looks as:
<?=Form::select('type_work[]', $work_types, old('type_work'), ['multiple' => "multiple", 'size' => 15, 'id' => 'type_work', "class" => "selectpicker form-control"]);?>
Where second parameter is incoming data to build options, and third parameter is array of selected options (id).
Why it does not work in Laravel?
This is incoming data:
Collection {#488 ▼
#items: array:14 [▼
14 => "Роботи, пов’язані з проведенням технічної експертизи."
]
}
This is selected data:
Collection {#408 ▼
#items: array:1 [▼
14 => "Роботи, пов’язані з проведенням технічної експертизи."
]
}
The amount type_work[] you have used is considered as the ID of the field. You must specify the value of the Name as an array.
Change the code as below
{{Form::select('type_work',$work_types,null,array('multiple'=>'multiple','name'=>'type_work[]'))}}
So you code should be like
<?=Form::select('type_work[]', $work_types, null, ['multiple' => true, 'size' => 15, 'id' => 'type_work', "class" => "selectpicker form-control"]);?>
Reference
Docs

Resources