Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - Validate birth date 18 years before today in rules request

Tags:

laravel

In Laravel 8 form request validation's rules, I have this birth date validation:

public function rules()
{
    return [
        'birth_date' => [
            'required',
            'before: date("Y-m-d")'
        ],
    ];
}

How do I validate it to be 18 years less than or equal to today's date?

like image 962
mikefolu Avatar asked Oct 20 '25 19:10

mikefolu


1 Answers

Use Carbon (built in to Laravel):

public function rules() {
  return [
    'birth_date' => [
      'required',
      'date_format:Y-m-d',
      'before:' . Carbon::now()->subYears(18)->format('Y-m-d')
    ],
  ];
}

This would generate before:2003-07-30. Make sure to include use Carbon\Carbon; at the top of this file, or do Carbon\Carbon::now()->subYears(18)->format('Y-m-d');

like image 164
Tim Lewis Avatar answered Oct 22 '25 23:10

Tim Lewis