I suggest a regular date to verify instead of separate fields. Just suggestion. .
Add DoB validation on UpdateUserProfile
Hi, I've added date of birth fields to User profile in a Laravel 9 Fortify/Livewire app and just want to add something sensible to check it's valid. DoB can also be null.
Here's my current UpdateUserProfileInformation.php file:
<?php
namespace App\Actions\Fortify;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Laravel\Fortify\Contracts\UpdatesUserProfileInformation;
class UpdateUserProfileInformation implements UpdatesUserProfileInformation
{
/**
* Validate and update the given user's profile information.
*
* @param mixed $user
* @param array $input
* @return void
*/
public function update($user, array $input)
{
Validator::make($input, [
'firstname' => ['required', 'string', 'max:255'],
'middlename' => ['nullable', 'string', 'max:255'],
'lastname' => ['required', 'string', 'max:255'],
'email' => ['required', 'email', 'max:255', Rule::unique('users')->ignore($user->id)],
'photo' => ['nullable', 'mimes:jpg,jpeg,png', 'max:1024'],
])->validateWithBag('updateProfileInformation');
if (isset($input['photo'])) {
$user->updateProfilePhoto($input['photo']);
}
if ($input['email'] !== $user->email &&
$user instanceof MustVerifyEmail) {
$this->updateVerifiedUser($user, $input);
} else {
$user->forceFill([
'firstname' => $input['firstname'],
'middlename' => $input['middlename'],
'lastname' => $input['lastname'],
'email' => $input['email'],
])->save();
}
}
/**
* Update the given verified user's profile information.
*
* @param mixed $user
* @param array $input
* @return void
*/
protected function updateVerifiedUser($user, array $input)
{
$user->forceFill([
'firstname' => $input['firstname'],
'middlename' => $input['middlename'],
'lastname' => $input['lastname'],
'email' => $input['email'],
'email_verified_at' => null,
])->save();
$user->sendEmailVerificationNotification();
}
}
My 3 DoB input fiels are Day (dob_day), Month (dob_month) and Year (dob_year) - I'm already doing some checking with JS to ensure that sensible values are entered - e.g. day must be a number and less than or equal to 31.
I think it's reasonable to allow date of birth where age would be between 18 and 100 - I'm comfortable using nabive PHP DateTime Class to do this but is there a more laravel way of doing it and how would I incorporate into my file above?
@the_lar first:
https://laravel.com/docs/9.x/requests#merging-additional-input
Then just use an if construct to check however you need on the date.
But step one is to ensure it's a valid date format.
Also see:
https://laravel.io/forum/laravel-date-validation-between-two-dates
Please or to participate in this conversation.