1
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?

Laravelの「mapメソッド」について

Last updated at Posted at 2024-06-29

はじめに

Laravelのコレクションは、データ操作を簡単にするための豊富なメソッドを提供しています。その中でもmapメソッドは、コレクション内の各アイテムに対して指定したコールバック関数を適用し、新しいコレクションを作成するために使用されます。mapは、変換や処理を行うための強力なツールです。

mapメソッドとは

mapメソッドは、コレクション内の各アイテムに対して指定されたコールバック関数を適用し、その結果を含む新しいコレクションを返します。元のコレクションは変更されず、処理結果を持つ新しいコレクションが返されるため、データ操作を安全に行うことができます。

基本的な使い方

例:コレクションの各アイテムを2倍にする例です。

配列の変換

use Illuminate\Support\Collection;

$collection = collect([1, 2, 3, 4, 5]);

$multiplied = $collection->map(function ($item) {
    return $item * 2;
});

print_r($multiplied->all()); // [2, 4, 6, 8, 10]

データベースクエリ結果の変換

データベースから取得した結果を処理する例です。

$users = DB::table('users')->get();

$transformed = $users->map(function ($user) {
    return [
        'user_id' => $user->id,
        'full_name' => $user->first_name . ' ' . $user->last_name,
    ];
});

print_r($transformed->all());

ネストされたデータの処理

ネストされた配列やオブジェクトの各要素に対して処理を行う例です。

$nested = collect([
    ['name' => 'alice', 'hobbies' => ['reading', 'swimming']],
    ['name' => 'bob', 'hobbies' => ['hiking', 'cycling']],
]);

$transformed = $nested->map(function ($item) {
    return [
        'name' => ucfirst($item['name']),
        'hobbies' => collect($item['hobbies'])->map(function ($hobby) {
            return ucfirst($hobby);
        })->all(),
    ];
});

print_r($transformed->all());
// [
//     ['name' => 'Alice', 'hobbies' => ['Reading', 'Swimming']],
//     ['name' => 'Bob', 'hobbies' => ['Hiking', 'Cycling']],
// ]

まとめ

Laravelのmapメソッドは、コレクションの各アイテムに対して指定した処理を適用し、新しいコレクションを作成するためのツールです。
mapメソッドを活用することで、効率的なデータ操作が可能になります。

1
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
1
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?