LoginSignup
1
0

More than 1 year has passed since last update.

【Laravel】日付に関するバリデーション判定集

Posted at

環境

Laravel v9.5.1 (PHP v8.1.3)

日付に関するバリデーション判定集

特定のユーザーの投稿を期間を指定して集計したいとき、$from$toに投げられるパラメータに日付ならではのバリデーションをつけたい。

$user->postAggregations
     ->whereBetween('created_at', [$from, $to]);

投げられた日付パラメータが

  • 「2022-1-1」のようなハイフン以外の場合
if (! DateTimeImmutable::createFromFormat('Y-m-d', $from) || ! DateTimeImmutable::createFromFormat('Y-m-d', $to)) {
    throw new InvalidDateFormatException();
}
  • 存在しない日付の場合
list($fromY, $fromM, $fromD) = explode('-', $from);
list($toY, $toM, $toD) = explode('-', $to);
if (! checkdate($fromM, $fromD, $fromY) || ! checkdate($toM, $toD, $toY)) {
    throw new InvalidDateFormatException();
}
  • 終了日が開始日より前の日付の場合
if ($from > $to) {
    throw new SpecifyEndDateAfterStartDateException();
}

さいごに

各処理をメソッドにしたり、$from$toをコンストラクタにしてクラスにしたりといろいろ使えると思います!

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