2
0

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 5 years have passed since last update.

Laravel5.8.4で追加されたCollectionのjoinメソッド

Posted at

Laravel 5.8.4がリリースされたので変更点を確認。

Collectionにjoinメソッド追加したよ的な記述があったので、implodeのaliasかなと思ったのですがコードをみるとちょっと挙動が違う。

確認したのでメモです。

まずはシンプルなコレクションを用意

>>> $collection = collect([1, 2, 3, 4, 5]);
=> Illuminate\Support\Collection {#3141
     all: [
       1,
       2,
       3,
       4,
       5,
     ],
   }

,で繋げてみる。これは両方同じ

>>> $collection->implode(', ');
=> "1, 2, 3, 4, 5"
>>> $collection->join(', ');
=> "1, 2, 3, 4, 5"

joinではもうひとつ引数を追加できる。日本語だと使いどころが無さそう気がする。

>>> $collection->join(', ', ' and ');
=> "1, 2, 3, 4 and 5"
>>> $collection->join('と', 'そして');
=> "1と2と3と4そして5"

ちょっと複雑なコレクションを用意

>>> $collection = collect([
...      ['account_id' => 1, 'product' => 'Desk'],
...      ['account_id' => 2, 'product' => 'Chair'],
...      ['account_id' => 3, 'product' => 'Hoge'],
... ]);
=> Illuminate\Support\Collection {#3168
     all: [
       [
         "account_id" => 1,
         "product" => "Desk",
       ],
       [
         "account_id" => 2,
         "product" => "Chair",
       ],
       [
         "account_id" => 3,
         "product" => "Hoge",
       ],
     ],
   }

implodeだと抜きだすキーを指定できますが、joinはできません

>>> $collection->implode('product', ', ')
=> "Desk, Chair, Hoge"
>>> $collection->join('product', ', ')
PHP Notice:  Array to string conversion in ...

joinでやるならpluckメソッドと組み合わせてこんな感じ

>>> $collection->pluck('product')->join(', ')
=> "Desk, Chair, Hoge"
>>> $collection->pluck('product')->join(', ', ' and ')
=> "Desk, Chair and Hoge"

join追加されましたがimplodeのaliasでは無いってことと使い所は無いかもってことがわかりました!

2
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?