Why can’t I overwrite a Collection in Laravel using the values() function?

Asked

Viewed 85 times

1

I’m trying to overwrite my Collection so she can receive herself with the keys reordered, the reason is that I’m giving a Forget() and sometimes the deleted element has a key value equal to 0 (zero), and my return array ends up starting with the value 1 (a), with the example below gets better to understand:

// Just for demonstration
$collection = collect([
    0 => ['nome' => 'Joao', 'idade' => 5],
    1 => ['nome' => 'Gabriel', 'idade' => 6]
]);

$collection->forget(0);

$collection = $collection->values();

return $collection->toArray();

/* Resultado retornado:
    [
             1 => ['nome' => 'Gabriel', 'idade' => 6]
    ]
*/

/* Resultado esperado:
    [
             0 => ['nome' => 'Gabriel', 'idade' => 6]
    ]
*/

But if I replace the return variable name, it returns the result correctly:

// Just for demonstration
$collection = collect([
    0 => ['nome' => 'Joao', 'idade' => 5],
    1 => ['nome' => 'Gabriel', 'idade' => 6]
]);

$collection->forget(0);

$values = $collection->values();

return $values->toArray();

/* Resultado retornado:
    [
             0 => ['nome' => 'Gabriel', 'idade' => 6]
    ]
*/
  • I don’t quite understand?

  • 1

    I want to replace the value of $Collection with the reordered ($Collection->values()), and Laravel is only leaving if I save this Collection with another variable name, I imagine it may be the version of Laravel.

1 answer

1


Everything you said is true and the solution is the same for the Laravel version 4.2:

The void method forget removes an item from the list by its key, its code is:

public function forget($key)
{
    unset($this->items[$key]);
}

and the method values() reset keys and return the collection class itself

public function values()
{
    $this->items = array_values($this->items);
    return $this; // retorna a instância atual
}

and actually if you do so:

$collection->forget(0);
$collection->values(); 
// pode continuar usando aqui a mesma variavel

the keys will be reset and the array will get organized.

Ref. Collection

Observing: there are actually differences in the versions of Laravel, clear example in Laravel 5.7 version the code is different and plays another instance of the class Collection, code:

public function values()
{
    return new static(array_values($this->items));
}

in a way you’re right because it will depend even on the version.

  • 1

    thank you very much, that cleared my doubts

Browser other questions tagged

You are not signed in. Login or sign up in order to post.