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

[12.x] Preserve item types (object or array) when using Arr::select() or Collection::select() #50772

Closed
wants to merge 2 commits into from

Conversation

Icexist
Copy link

@Icexist Icexist commented Mar 26, 2024

This PR proposes a change to maintain the type of an array or collection value upon return from the select method.

Existing behavior converts all values returned from select as arrays.


10.44.0 added the Collection::select() and Arr::select() methods #49845 and 10.45.0 updated it to work with ArrayAccess #50072

However, these convert any item in either an array or the Collection into an array even if it is an object. See https://github.com/laravel/framework/blob/master/src/Illuminate/Collections/Arr.php#L532-L533

For example, if you have an array of objects and select a single column, it will become an array of arrays.

$obj1 = new \stdClass;
$obj1->color = 'blue';
$obj1->temperature = 'warm';

$obj2 = new \stdClass;
$obj2->color = 'green';
$obj2->temperature = 'cool';

$arr = [$obj1, $obj2];

$selected = Arr::select($arr, 'color');
/* 
[
    [ 'color' => 'blue' ],
    [ 'color' => 'green' ],
]
*/

This is unexpected behavior as the Collection returned from Query Builder has each row of data represented as a stdClass object. Using select on that Collection then converts all the stdClass objects to array types, breaking downstream code.

The proposed change would coerce the individual value of the Collection or Array back into an object if the value was originally an object.

Previously #50749 as a change to 11.x.

@driesvints driesvints changed the title Preserve item types (object or array) when using Arr::select() or Collection::select() [11.x] Preserve item types (object or array) when using Arr::select() or Collection::select() Mar 26, 2024
@taylorotwell
Copy link
Member

This would be a breaking change to apps that are working around this.

@decadence
Copy link
Contributor

Title is wrong. It's for master, not for 11.x

@Icexist
Copy link
Author

Icexist commented Mar 26, 2024

I agree, but @driesvints changed it so I'm reluctant to switch it back. Especially after Taylor closed it.

@crynobone crynobone changed the title [11.x] Preserve item types (object or array) when using Arr::select() or Collection::select() [12.x] Preserve item types (object or array) when using Arr::select() or Collection::select() Mar 26, 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.

None yet

3 participants