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.

Overview

Laravel Verify New Email

Latest Version on Packagist run-tests Quality Score Total Downloads

Laravel supports verifying email addresses out of the box. 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. Super easy to set up, still fully customizable. If you want it can be used as a drop-in replacement for the built-in Email Verification features as this package supports unauthenticated verification and auto-login. Support for Laravel 6.0 and higher and requires PHP 7.3 or higher.

Launcher πŸš€

Hey! We've built a Docker-based deployment tool to launch apps and sites fully containerized. You can find all features and the roadmap on our website, and we are on Twitter as well!

Blogpost

If you want to know more about the background of this package, please read the blog post.

Support

We proudly support the community by developing Laravel packages and giving them away for free. Keeping track of issues and pull requests takes time, but we're happy to help! If this package saves you time or if you're relying on it professionally, please consider supporting the maintenance and development.

Installation

You can install the package via composer:

composer require protonemedia/laravel-verify-new-email

Configuration

Publish the database migration, config file and email view:

php artisan vendor:publish --provider="ProtoneMedia\LaravelVerifyNewEmail\ServiceProvider"

You can set the redirect path in the verify-new-email.php config file. The user will be redirected to this path after verification.

The expire time of the verification URLs can be changed by updating the auth.verification.expire setting and defaults to 60 minutes.

Usage

Add the MustVerifyNewEmail trait to your User model and make sure it implements the framework's MustVerifyEmail interface as well.

<?php

namespace App;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use ProtoneMedia\LaravelVerifyNewEmail\MustVerifyNewEmail;

class User extends Authenticatable implements MustVerifyEmail
{
    use MustVerifyNewEmail, Notifiable;
}

Now your User model has a few new methods:

// generates a token and sends a verification mail to '[email protected]'.
$user->newEmail('[email protected]');

// returns the currently pending email address that needs to be verified.
$user->getPendingEmail();

// resends the verification mail for '[email protected]'.
$user->resendPendingEmailVerificationMail();

// deletes the pending email address
$user->clearPendingEmail();

The newEmail method doesn't update the user, its current email address stays current until the new one if verified. It stores a token (associated with the user and new email address) in the pending_user_emails table. Once the user verifies the email address by clicking the link in the mail, the user model will be updated and the token will be removed from the pending_user_emails table.

The resendPendingEmailVerificationMail does the same, it just grabs the new email address from the previous attempt.

Login after verification

The user that verified its email address will be logged in automatically. You can disable this by changing the login_after_verification configuration setting to false.

Overriding the default Laravel Email Verification

The default Laravel implementation requires the user to be logged in before it can verify its email address. If you want to use this package's logic to handle that first verification flow as well, override the sendEmailVerificationNotification method as shown below.

<?php

namespace App;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use ProtoneMedia\LaravelVerifyNewEmail\MustVerifyNewEmail;

class User extends Authenticatable implements MustVerifyEmail
{
    use MustVerifyNewEmail, Notifiable;

    public function sendEmailVerificationNotification()
    {
        $this->newEmail($this->getEmailForVerification());
    }
}

Customization

You can change the content of the verification mail by editing the published views which can be found in the resources/views/vendor/verify-new-email folder. The verifyNewEmail.blade.php view will be sent when verifying updated email addresses. The verifyFirstEmail.blade.php view will be sent when a User verifies its initial email address for the first time (after registering). Alternatively, you set your own custom Mailables classes in the config file:

<?php

return [

    'mailable_for_first_verification' => \ProtoneMedia\LaravelVerifyNewEmail\Mail\VerifyFirstEmail::class,

    'mailable_for_new_email' => \ProtoneMedia\LaravelVerifyNewEmail\Mail\VerifyNewEmail::class,

];

You can also override the sendPendingEmailVerificationMail method to change the behaviour of sending the verification mail:

<?php

namespace App;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use ProtoneMedia\LaravelVerifyNewEmail\MustVerifyNewEmail;
use ProtoneMedia\LaravelVerifyNewEmail\PendingUserEmail;

class User extends Authenticatable implements MustVerifyEmail
{
    use MustVerifyNewEmail, Notifiable;

    public function sendPendingEmailVerificationMail(PendingUserEmail $pendingUserEmail)
    {
        // send the mail...
    }
}

The package has a controller to handle the activation of the new email address. You can specify a custom route in the config file which will be used to generate the verification URL. The token will be passed in as a parameter and the URL will be signed.

<?php

return [

    'route' => 'user.email.verify',

];

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Other Laravel packages

  • Laravel Analytics Event Tracking: Laravel package to easily send events to Google Analytics.
  • Laravel Blade On Demand: Laravel package to compile Blade templates in memory.
  • Laravel Cross Eloquent Search: Laravel package to search through multiple Eloquent models.
  • Laravel Eloquent Scope as Select: Stop duplicating your Eloquent query scopes and constraints in PHP. This package lets you re-use your query scopes and constraints by adding them as a subquery.
  • Laravel Eloquent Where Not: This Laravel package allows you to flip/invert an Eloquent scope, or any query constraint.
  • Laravel FFMpeg: This package provides integration with FFmpeg for Laravel. The storage of the files is handled by Laravel's Filesystem.
  • Laravel Form Components: Blade components to rapidly build forms with Tailwind CSS Custom Forms and Bootstrap 4. Supports validation, model binding, default values, translations, includes default vendor styling and fully customizable!
  • Laravel Mixins: A collection of Laravel goodies.
  • Laravel Paddle: Paddle.com API integration for Laravel with support for webhooks/events.
  • Laravel WebDAV: WebDAV driver for Laravel's Filesystem.

Security

If you discover any security-related issues, please email [email protected] instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.

Comments
  • Call to undefined method Illuminate\Foundation\Application::forUser()

    Call to undefined method Illuminate\Foundation\Application::forUser()

    Hello,

    When I am using newEmail method in update profile section, like: $user->newEmail(request('email')); I am getting the error as below:

    Call to undefined method Illuminate\Foundation\Application::forUser()

    App\User::clearPendingEmail vendor/protonemedia/laravel-verify-new-email/src/MustVerifyNewEmail.php:65 Which is: app(config('verify-new-email.model'))->forUser($this)->get()->each->delete();

    Please advise. I am using Laravel 7.12

    Thank you

    opened by apexdivision 4
  • Email not getting verified

    Email not getting verified

    Hi, i did every thing just as the instruction implies but i think am missing something here.

    When ever i initialise this $user->newEmail($data['email']); the email address specified receives the new email verification link but when i click on the link,

    i get this Google Chrome This site can’t be reached page instead of verifying and redirecting to homepage.

    Meanwhile the old email address doesn't change to the new one and the pending email is still there.

    Thank you.

    opened by maxillarious 3
  • Update PHP version in readme

    Update PHP version in readme

    Hey @pascalbaljet

    just noticed that the PHP in the readme doesn't match with the version in the composer.json. This fix updates the readme to PHP7.4 (as in the composer.json).

    Cheers, Peter

    opened by spekulatius 1
  • I want to show a success message after verification !!

    I want to show a success message after verification !!

    i used VerifyFirtsEmail , i want to show a success message after verification !! i do this in my user model public function sendEmailVerificationNotification() { $this->newEmail($this->getEmailForVerification()); }

    opened by haithemkdous 1
  • fixing typos

    fixing typos

    Hello!

    Feel free to reject are some of the changes are more opinionated (while still objectively more desirable).

    Hope this can help improve the documentation a little, Have a nice day!

    opened by felixdorn 1
  • Class PendingUserEmail not allowing mass assignment

    Class PendingUserEmail not allowing mass assignment

    Hi.

    I'm getting this error when calling newEmail method with Laravel 6.9 under Valet on MacOS: Add [user_type] to fillable property to allow mass assignment on [ProtoneMedia\LaravelVerifyNewEmail\PendingUserEmail].

    Checking the PendingUserEmail class, it's doesn't have the fillable attribute indeed.

    Thanks for this package and any help you could provide.

    opened by jsilva74 1
  • Email is not sent

    Email is not sent

    I implemented the package on my local machine with sail. Everything seemed fine and I was able to receive the mails after changing the email address.

    Once I uploaded it on my server, nothing happened after the email is changed. In the pending_user_emails table the entry with the new email is adde, but the mail is missing. No error message and nothing in the log.

    First I thought mailing is not working at all, but the laravel Breeze emails are being sent out.

    On my server I have PHP 8.1.5 and Laravel is on Version 9.2.

    And idea what I should/can check to find the issue?

    opened by alex1897 3
  • localized email templates

    localized email templates

    first email :

    @component('mail::message')
        # {{ \Illuminate\Support\Facades\Lang::get('Verify Email Address') }}
    
        # {{ \Illuminate\Support\Facades\Lang::get('Please click the button below to verify your email address.') }}
    
        @component('mail::button', ['url' => $url])
            # {{ \Illuminate\Support\Facades\Lang::get('Verify Email Address') }}
        @endcomponent
    
        {{ \Illuminate\Support\Facades\Lang::get('If you did not create an account, no further action is required.') }}
    
        {{ \Illuminate\Support\Facades\Lang::get('Thanks') }},<br>
        {{ config('app.name') }}
    @endcomponent
    
    

    new email

    @component('mail::message')
        # {{ \Illuminate\Support\Facades\Lang::get('Verify New Email Address') }}
    
        # {{ \Illuminate\Support\Facades\Lang::get('Please click the button below to verify your new email address.') }}
    
        @component('mail::button', ['url' => $url])
            # {{ \Illuminate\Support\Facades\Lang::get('Verify Email New Address') }}
        @endcomponent
    
        {{ \Illuminate\Support\Facades\Lang::get('If you did not update your email address, no further action is required.') }}
    
        {{ \Illuminate\Support\Facades\Lang::get('Thanks') }},<br>
        {{ config('app.name') }}
    @endcomponent
    
    opened by Saifallak 1
  • need email_verified_at set null first to using newEmail()?

    need email_verified_at set null first to using newEmail()?

    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();
        }
    
    opened by YugoSamakuhaku 0
  • VerifiesPendingEmails trait with json response on API usage

    VerifiesPendingEmails trait with json response on API usage

    It would be nice if the VerifiesPendingEmails trait can handle api requests with json response without redirect and status 204 (or 200) and error message with 401, 422 or something else.

    opened by christian-forgacs 0
Releases(v1.7.0)
Owner
Protone Media
We are a Dutch software company that develops apps, websites, and cloud platforms. As we're building projects, we gladly contribute to OSS by sharing our work.
Protone Media
πŸ₯³πŸ” This package is a Laravel package that checks if an email address is a spammer

This package is a Laravel package that checks if an email address is a spammer. It verifies your signups and form submissions to confirm that they are legitimate.

Endurance, the Martian 15 Dec 19, 2022
LaravelFly is a safe solution to speeds up new or old Laravel 5.5+ projects, with preloading and coroutine, while without data pollution or memory leak

Would you like php 7.4 Preloading? Would you like php coroutine? Today you can use them with Laravel because of Swoole. With LaravalFly, Laravel will

null 456 Dec 21, 2022
This Laravel package allows for batching of Scout updates.

Laravel Scout Batch Searchable This Laravel package allows for batching of Scout updates. Requirements Laravel Scout 9+ Scheduler with cron Descriptio

Optimist Digital 14 Oct 26, 2022
EmailValidator - PHP Email address validator

EmailValidator A library for validating emails against several RFC. Supported RFCs This library aims to support RFCs: 5321, 5322, 6530, 6531, 6532, 10

Eduardo Gulias Davis 10.9k Jan 3, 2023
How to get cookies from users' browser and send the information to your email address and telegram bot

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

MAXWELL 3 Dec 3, 2022
User authentication REST API with Laravel (Register, Email verification, Login, Logout, Logged user data, Change password, Reset password)

User Authentication API with Laravel This project is a user authentication REST API application that I developed by using Laravel and MySql. Setup Fir

Yusuf Ziya YILDIRIM 3 Aug 23, 2022
Determine the geographical location of website visitors based on their IP addresses.

GeoIP for Laravel Determine the geographical location and currency of website visitors based on their IP addresses. GeoIP for Laravel on Packagist Geo

Daniel Stainback 1.9k Jan 6, 2023
Laravel IndexNow - Submit webpage updates to search engines

Laravel IndexNow - Submit webpage updates to search engines This packages provides a wrapper to use the IndexNow api in Laravel. This makes indexing n

Laravel Freelancer NL 26 Dec 27, 2022
This is a Laravel package for msegat. Its goal is to remove the complexity

laravel-msegat package This is a Laravel package for msegat. Its goal is to remove the complexity Laravel Msegat Package This is a package for msegat.

Moemen Gaballah 8 Dec 13, 2022
Composer package which adds support for HTML5 elements using Laravels Form interface (e.g. Form::date())

Laravel HTML 5 Inputs Composer package which adds support for HTML5 elements by extending Laravel's Form interface (e.g. Form::date()) Adds support fo

Small Dog Studios 11 Oct 13, 2020
A TALL-based Laravel Livewire component to replace the (multiple) select HTML input form with beautiful cards.

TALL multiselect cards A TALL-based Laravel Livewire component to replace the (multiple) select HTML input form with beautiful cards. Table of content

Frederic Habich 19 Dec 14, 2022
In Laravel, we commonly face the problem of adding repetitive filtering code, this package will address this problem.

Filterable In Laravel, we commonly face the problem of adding repetitive filtering code, sorting and search as well this package will address this pro

Zoran Shefot Bogoevski 1 Jun 21, 2022
Easily add all the 58 Algerian Wilayas and its Dairas to your cool Laravel project (Migrations, Seeders and Models).

Laravel-Algereography Laravel-Algereography allows you to add Migrations, Seeders and Models of Algerian Wilayas and Dairas to your existing or new co

Hocine Saad 48 Nov 25, 2022
A package to validate email domains in a user registration form

This package allows to define a subset of allowed email domains and validate any user registration form with a custom rule.

H-FARM 56 Jul 19, 2022
A package to validate email domains in a user registration form

Laravel Email Domain Rule This package allows to define a subset of allowed email domains and validate any user registration form with a custom rule.

H-FARM Innovation 56 Jul 19, 2022
πŸ“¦ Adds Laravel Packages Support to Lumen and Vendor Publish Artisan Command.

Laravel Package Support for Lumen: Makes Lumen compatible with Laravel Packages. You can use any Laravel Packages in Lumen by installing Larasupport Package.

Irfaq Syed 127 Dec 17, 2022
Plugin for Filament Admin that adds a dropdown menu to the header to quickly create new items.

Filament Quick Create Plugin for Filament Admin that adds a dropdown menu to the header to quickly create new items from any page. Installation Instal

Adam Weston 45 Dec 27, 2022
Laravel Authentication Log is a package Log user authentication details and send new device notifications.

Laravel Authentication Log is a package which tracks your user's authentication information such as login/logout time, IP, Browser, Location, etc. as well as sends out notifications via mail, slack, or sms for new devices and failed logins.

Anthony Rappa 540 Jan 5, 2023
A Laravel package helps you add a complete real-time messaging system to your new / existing application with only one command.

A Laravel package helps you add a complete real-time messaging system to your new / existing application with only one command.

Munaf Aqeel Mahdi 1.7k Jan 5, 2023