Search code examples
phparrayslaravelhelper

How to return a string in indices that are array in Laravel 7


I would like to know how I can return a string, for any part of my request that is an array.
The request could contain any keys, so I can't hard code it.

Example of what I have done so far.

$request = [
    'empresaId' => '2',
    'entidadeId' => [
        '507-2',
        '1422-2',
    ],
    'dataInicio' => '2021-05-27',
    'dataFim' => '2021-05-31',
];

$requestFiltered = Arr::where($request->all(), function($value, $key) { 
    if (!is_null($value) && ($key != '_token')) {
        if (is_array($value)) {
            return collect($value)->implode(',');
        }
        return $value;
    }
});

This doesn't return the data in the way that I expect.
I'm not sure what I'm doing wrong.

This is an example of how I expect the array to be returned.

[
    'empresaId' => '2',
    'entidadeId' => '507-2,1422-2',
    'dataInicio' => '2021-05-27',
    'dataFim' => '2021-05-31',
]

Solution

  • You are nearly there, you could just use map instead of where.

    where is not used to mutate the data, it is meant to just query the data, so you are only supposed to return a Boolean in the closure.
    map and transform will mutate your data.

    $requestFiltered = collect($request->all())->map(function ($item, $key) {
        // Ignore tokens.
        if (Str::endsWith($key, '_token')) {
            return;
        }
    
        // Check for arrays, then implode.
        if (is_array($item)) {
            return implode(',', $item);
        }
    
        return $item;
    })