Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace spread operator with union operator #22

Merged
merged 2 commits into from
Mar 21, 2024

Conversation

CharlieEtienne
Copy link
Contributor

Hi @rupadana ,

I just noticed that Users ids were not preserved when the form was submitted.

This happens because spread operator (...), just like array_merge, is not preserving the array keys when they are numerical.

The proposed solution is to replace that with an array union operator (+).

@rupadana
Copy link
Owner

can you please refer some screenshot of the bug?

cause i dont see the issue

@CharlieEtienne
Copy link
Contributor Author

If you select users having ids 1 and 3 and dump you can see it.

Example:

dd(User::all()->pluck('name', 'id'));

will give you

Illuminate\Support\Collection {#2858 ▼ // routes/web.php:35
  #items: array:12 [▼
    1 => "User 1"
    3 => "User 3"
  ]
  #escapeWhenCastingToString: false
}

but when you do:

dd(['all' => 'all', ...User::all()->pluck('name', 'id')]);

this is what you get:

array:13 [▼ // routes/web.php:35
  "all" => "all"
  0 => "User 1"
  1 => "User 3"
]

Notice how 1 becomes 0 and 3 becomes 1.

The result is only user having ID 1 being notified.

@CharlieEtienne
Copy link
Contributor Author

You can easily test it in your own code base if you paste this in your route file:

Route::get('/tinker', function () {
    $users = User::query()->whereIn('id', [1,3])->pluck('name', 'id')->toArray();

    echo '<h2>Users query</h2>';
    echo '<pre>$users = User::query()->whereIn(\'id\', [1,3])->pluck(\'name\', \'id\')->toArray();</pre>';
    echo '<pre>dump($users);</pre>';

    dump($users);

    echo '<h2>Current implementation (with spread operator)</h2>';
    echo '<pre>dump([\'all\' => \'all\', ...$users]);</pre>';

    dump(['all' => 'all', ...$users]);

    echo '<h2>Proposed solution (with array union operator)</h2>';
    echo '<pre>dump([\'all\' => \'all\'] + $users);</pre>';

    dump(['all' => 'all'] + $users);
});

@rupadana
Copy link
Owner

I see, You are right, let's merge it.

Thank you for your explanation and contribution 😄

@rupadana rupadana merged commit 22e81ad into rupadana:main Mar 21, 2024
6 checks passed
@rupadana rupadana mentioned this pull request Aug 6, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants