Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel collections mapWithKeys

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
)
like image 974
Saravanan Sampathkumar Avatar asked Feb 01 '17 12:02

Saravanan Sampathkumar


People also ask

How do I count collections in laravel?

$coll = User::all(); echo $coll->count();

How can a function return multiple values in laravel?

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.

What is the use of collect () in laravel?

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.

What is map function in laravel?

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.


1 Answers

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');
like image 140
Alexey Mezenin Avatar answered Sep 30 '22 20:09

Alexey Mezenin