I have been trying to create an array using laravel's collection function called mapWithKeys, but I couldn't achieve what I need.
Here is my code,
$years = range(1900, date('Y'));
return collect($years)->mapWithKeys(function($value){
return [$value => $value];
})->all();
Expected result
Array
(
[1900] => 1900
[1901] => 1901
[1902] => 1902
....
[2017] => 2017
)
But what I get is
Array
(
[0] => 1900
[1] => 1901
[2] => 1902
...
[117] => 2017
)
$coll = User::all(); echo $coll->count();
Possible solution is that you define private/protected variables as a and b within the class and in the method totalStocks() you can set values to them. So you can access $this->a and $this->b as properties of the class whenever class is in use. Save this answer.
Laravel collections can be regarded as modified versions of PHP arrays. They are located in the Illuminate\Support\Collection directory and provide a wrapper to work with data arrays. In the code snippet above, we used the collect() method to create a Collection instance from the defined array.
Laravel map() is a Laravel Collections method to pass callback function to each item in Collection. It is a easy yet powerful method to manipulate data in Laravel Collection. After operating on each item, map() method returns new Collection object with updated items.
I've tested this code and it works perfectly:
$years = range(1900, date('Y'));
return collect($years)->map(function($i) {
return ['year' => $i];
}, $years)->pluck('year', 'year');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With