protonemedia / laravel-verify-new-email

This package adds support for verifying new email addresses: when a user updates its email address, it won't replace the old one until the new one is verified.
https://protone.media/en/blog/an-add-on-to-laravels-built-in-email-verification-only-update-a-users-email-address-if-the-new-one-is-verified-as-well
MIT License
404 stars 30 forks source link

need email_verified_at set null first to using newEmail()? #14

Open YugoSamakuhaku opened 2 years ago

YugoSamakuhaku commented 2 years ago

I use livewire, when updating an email I use

   if ($this->email != $this->user->email) {
             $this->user->email_verified_at = null;
             $this->user->newEmail($this->user->email);
  }

if email_verified_at is not set to null, newEmail() will not create a new record in the pending_user_emails table

this is my edit file

class Edit extends Component {
    public User $user;

    public $roles          = [];
    public $listsForFields = [];

    public $password              = '';
    public $password_confirmation = '';

    public $email = '';

    public function mount(User $user) {
        $this->user  = $user;
        $this->email = $this->user->email;
        $this->roles = $this->user->roles()->pluck('id')->toArray();
        $this->initListsForFields();
    }

    public function render() {
        return view('livewire.user.edit');
    }

    public function submit() {
        $this->validate();
        $this->user->password = $this->password;

        if ($this->email != $this->user->email) {
            $this->user->email_verified_at = null;
            $this->user->newEmail($this->user->email);
        } else {
            $this->user->save();
        }
        $this->user->roles()->sync($this->roles);

        return redirect()->route('users.index');
    }

    protected function rules() {
        return [
            'user.name'             => ['required', 'string', 'max:255'],
            'user.email'            => ['required', 'email', 'max:255', 'unique:users,email,' . $this->user->id],
            'user.biography'        => ['nullable'],
            'roles'                 => ['required', 'array'],
            'roles.*.id'            => ['integer', 'exists:roles,id'],
            'password'              => ['string', 'min:8', 'confirmed'],
            'password_confirmation' => ['string', 'min:8'],
        ];
    }

    public function initListsForFields(): void {
        $this->listsForFields['roles'] = Role::pluck('name', 'id')->toArray();
    }