2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Laravel】Collection内のオブジェクトを操作する

Posted at

はじめに

Laravelでの開発中に、配列内の各オブジェクトにデータを追加する処理を実装する際に、以下のようなコードで実装を行った。

        $collection = new Collection([
            { id: 1, name: '田中' },
            { id: 2, name: '佐藤'}
        ]);
        foreach ($collection as $object) {
            $object->new_data = 'hoge';
        }
        /* 
         $collection = [
            { id: 1, name: '田中', new_data: 'hoge' },
            { id: 2, name: '佐藤', new_data: 'hoge' }
         ]
        */

これでプルリクを投げたらレビュアーからこんな指摘が↓

これ、Collectionのmap使えばforeachで回さなくてもできるよ

え、Collectionってそんなこともできるのか!!!(小並感)

ということで実際にやってみた。

参考

やり方

※Laravelのバージョンは6.0です。

        $collection = new Collection([
            { id: 1, name: '田中' },
            { id: 2, name: '佐藤'}
        ]);

        $collection->map(function ($object) {
            $object->newdata = 'hoge';
        });
        /* 
         $collection = [
            { id: 1, name: '田中', new_data: 'hoge' },
            { id: 2, name: '佐藤', new_data: 'hoge' }
         ]
        */

オブジェクトでもarray_mapみたいに処理をかけるのは嬉しい・・・😭

Collectionでは、配列だと実現がめんどくさい処理も簡単にできるようになっていて、使いこなせるようになるとだいぶ開発が楽になるなと感じました。

ホント、Laravelしゅごい

みなさんも是非Collectionをマスターして、快適なLaravel開発ライフを!(僕自身全然マスターできていませんが・・・)

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?