abdalla arbab abdalla arbab - 2 months ago 19
PHP Question

How to map multiple request using collections

I have a time request from multiple time inputs

<form>
...
<input type="text" name="times[]">
<input type="text" name="times[]">
...
</form>


And in my controller
dd($request->times)
looks like this

array:3 [
0 => "2:25 AM"
1 => "5:35 AM"
2 => "5:40 AM"
]


How can I map this request using laravel collection into this

[
[
'time' => '2:25 AM',
],
[
'time' => '5:35 AM',
],
[
'time' => '5:40 AM',
],
]


I tried this

$timesArray = collect([$request->times]);
$times = $timesArray->mapWithKeys(function ($item, $key) {
return [ 'time' => $item[$key] ];
})->toArray();


But it only returning

array:1 [
"time" => "2:25 AM"
]


Thanks.

Answer Source

You don't need to use mapWithKeys, you are trying to map array values without keys, so map will do.

$times = collect($request->times)
    ->map(function ($time) {
        return [ 'time' => $time ];
    })
    ->toArray();

Also, $request->times is already an array, so you don't have to wrap this in square brackets again or you are creating an array in an array.