4
4
5
5
use ArgumentCountError ;
6
6
use ArrayAccess ;
7
+ use Closure ;
7
8
use Illuminate \Contracts \Support \Arrayable ;
8
9
use Illuminate \Contracts \Support \Jsonable ;
9
10
use Illuminate \Support \Traits \Macroable ;
@@ -686,8 +687,8 @@ public static function select($array, $keys)
686
687
* Pluck an array of values from an array.
687
688
*
688
689
* @param iterable $array
689
- * @param string|array|int|null $value
690
- * @param string|array|null $key
690
+ * @param string|array|int|Closure| null $value
691
+ * @param string|array|Closure| null $key
691
692
* @return array
692
693
*/
693
694
public static function pluck ($ array , $ value , $ key = null )
@@ -697,15 +698,19 @@ public static function pluck($array, $value, $key = null)
697
698
[$ value , $ key ] = static ::explodePluckParameters ($ value , $ key );
698
699
699
700
foreach ($ array as $ item ) {
700
- $ itemValue = data_get ($ item , $ value );
701
+ $ itemValue = $ value instanceof Closure
702
+ ? $ value ($ item )
703
+ : data_get ($ item , $ value );
701
704
702
705
// If the key is "null", we will just append the value to the array and keep
703
706
// looping. Otherwise we will key the array using the value of the key we
704
707
// received from the developer. Then we'll return the final array form.
705
708
if (is_null ($ key )) {
706
709
$ results [] = $ itemValue ;
707
710
} else {
708
- $ itemKey = data_get ($ item , $ key );
711
+ $ itemKey = $ key instanceof Closure
712
+ ? $ key ($ item )
713
+ : data_get ($ item , $ key );
709
714
710
715
if (is_object ($ itemKey ) && method_exists ($ itemKey , '__toString ' )) {
711
716
$ itemKey = (string ) $ itemKey ;
@@ -721,15 +726,15 @@ public static function pluck($array, $value, $key = null)
721
726
/**
722
727
* Explode the "value" and "key" arguments passed to "pluck".
723
728
*
724
- * @param string|array $value
725
- * @param string|array|null $key
729
+ * @param string|array|Closure $value
730
+ * @param string|array|Closure| null $key
726
731
* @return array
727
732
*/
728
733
protected static function explodePluckParameters ($ value , $ key )
729
734
{
730
735
$ value = is_string ($ value ) ? explode ('. ' , $ value ) : $ value ;
731
736
732
- $ key = is_null ($ key ) || is_array ($ key ) ? $ key : explode ('. ' , $ key );
737
+ $ key = is_null ($ key ) || is_array ($ key ) || $ key instanceof Closure ? $ key : explode ('. ' , $ key );
733
738
734
739
return [$ value , $ key ];
735
740
}
0 commit comments