diff --git a/src/Illuminate/Support/Collection.php b/src/Illuminate/Support/Collection.php index b8d68563d9ff..be7bc77c4d1e 100644 --- a/src/Illuminate/Support/Collection.php +++ b/src/Illuminate/Support/Collection.php @@ -821,6 +821,19 @@ public function flatMap(callable $callback) return $this->map($callback)->collapse(); } + /** + * Map the values into a new class. + * + * @param string $class + * @return static + */ + public function mapInto($class) + { + return $this->map(function ($value, $key) use ($class) { + return new $class($value, $key); + }); + } + /** * Get the max value of a given key. * diff --git a/tests/Support/SupportCollectionTest.php b/tests/Support/SupportCollectionTest.php index f7de5cfee6a3..9f1cfd32bfb2 100755 --- a/tests/Support/SupportCollectionTest.php +++ b/tests/Support/SupportCollectionTest.php @@ -1209,6 +1209,18 @@ public function testMapWithKeysCallbackKey() ); } + public function testMapInto() + { + $data = new Collection([ + 'first', 'second', + ]); + + $data = $data->mapInto(TestCollectionMapIntoObject::class); + + $this->assertEquals('first', $data[0]->value); + $this->assertEquals('second', $data[1]->value); + } + public function testNth() { $data = new Collection([ @@ -2200,3 +2212,13 @@ public function jsonSerialize() return ['foo' => 'bar']; } } + +class TestCollectionMapIntoObject +{ + public $value; + + public function __construct($value) + { + $this->value = $value; + } +}