0
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でよく使う each() メソッドと Carbon の基本をまとめてみた【日付操作と配列処理】

Posted at

はじめに

LaravelやPHPを使って開発をしていると、

  • $collection->each(...)
  • Carbon::now()

といったコードをよく見かけます。

この記事では、Laravelでよく使われる each() メソッドと Carbon インスタンスの基本的な使い方や意味について解説します。


each() メソッドとは?

each() は、コレクション(配列のようなデータ構造)に対して、1つずつ処理を行うためのメソッドです。

Laravelのコレクション(Illuminate\Support\Collection)でよく使われます。

基本構文:

$collection->each(function ($item, $key) {
    // ここで処理
});

使用例:

$users = collect([
    ['name' => '田中'],
    ['name' => '佐藤'],
    ['name' => '鈴木'],
]);

$users->each(function ($user) {
    echo $user['name'] . "\n";
});

出力:

田中
佐藤
鈴木

each() と foreach の違い

IMG_4030.jpeg

each() はメソッドチェーン可能な「Laravel流」な書き方としてよく使われます。

③Carbon インスタンスとは?

Laravelでは、日付・時刻の操作にCarbon(カルボン)というライブラリが標準で使われています。
これは DateTime クラスを拡張した強力なツールで、直感的かつ読みやすい日付操作が可能です。
基本構文:

use Carbon\Carbon;

$now = Carbon::now();

これで $now は、現在日時を持つCarbonインスタンスになります。

よく使うメソッド・プロパティ

IMG_4031.jpeg

Carbon × each の組み合わせ例

$dates = collect([
    '2025-01-01',
    '2025-02-01',
    '2025-03-01'
]);

$dates->each(function ($date) {
    $carbonDate = Carbon::parse($date);
    echo $carbonDate->format('Y年m月d日') . "\n";
});

④まとめ

each()

  • LaravelのCollection専用のループメソッド
  • foreach よりも「チェーンしやすく、読みやすい」
  • よくBladeテンプレートやデータ処理で登場

Carbon

  • Laravel標準の日付・時間操作ライブラリ
  • Carbon::now() で現在日時がすぐ取れる
  • addDays(), diffForHumans() など便利メソッドが豊富
0
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
0
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?