LoginSignup
6
5

More than 3 years have passed since last update.

PHP - 年齢の範囲検索を生年月日から行う

Last updated at Posted at 2018-04-20

Carbonを使います。

\$age['from']歳から$age['to']歳までを検索するとき

test.php
    if (!empty($age)){
            if(!empty($age['from'])){
                $latestBirthday = Carbon::now()->subYear($age['from'])->format('Y-m-d');
                $user->where('birthday', '<=', $latestBirthday);
            }
            if(!empty($age['to'])){
                $earliestBirthday = Carbon::now()->subYear($age['to'] + 1)->addDay()->format('Y-m-d');
                $user->where('birthday', '>=', $earliestBirthday);
            }
        }

考え方としては

  • \$age['from']歳の人の誕生日で一番新しい日より古い誕生日の人
  • \$age['to']歳の人の誕生日で一番古いより新しい誕生日の人

を検索してるだけです。

6
5
1

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
6
5