├── .github ├── FUNDING.yml └── workflows │ └── run-tests.yml ├── src ├── InvalidEmailVerificationModelException.php ├── Http │ ├── InvalidVerificationLinkException.php │ ├── VerifyNewEmailController.php │ └── VerifiesPendingEmails.php ├── routes.php ├── Mail │ ├── VerifyNewEmail.php │ └── VerifyFirstEmail.php ├── ServiceProvider.php ├── PendingUserEmail.php └── MustVerifyNewEmail.php ├── resources └── views │ ├── verifyFirstEmail.blade.php │ └── verifyNewEmail.blade.php ├── database └── migrations │ └── create_pending_user_emails_table.php.stub ├── .phpunit.result.cache ├── LICENSE.md ├── config └── config.php ├── CHANGELOG.md ├── composer.json ├── CONTRIBUTING.md └── README.md /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: [pascalbaljet] 2 | -------------------------------------------------------------------------------- /src/InvalidEmailVerificationModelException.php: -------------------------------------------------------------------------------- 1 | middleware(['web', 'signed']) 8 | ->name('pendingEmail.verify'); 9 | -------------------------------------------------------------------------------- /resources/views/verifyFirstEmail.blade.php: -------------------------------------------------------------------------------- 1 | @component('mail::message') 2 | # Verify Email Address 3 | 4 | Please click the button below to verify your email address. 5 | 6 | @component('mail::button', ['url' => $url]) 7 | Verify Email Address 8 | @endcomponent 9 | 10 | If you did not create an account, no further action is required. 11 | 12 | Thanks,
13 | {{ config('app.name') }} 14 | @endcomponent -------------------------------------------------------------------------------- /resources/views/verifyNewEmail.blade.php: -------------------------------------------------------------------------------- 1 | @component('mail::message') 2 | # Verify New Email Address 3 | 4 | Please click the button below to verify your new email address. 5 | 6 | @component('mail::button', ['url' => $url]) 7 | Verify New Email Address 8 | @endcomponent 9 | 10 | If you did not update your email address, no further action is required. 11 | 12 | Thanks,
13 | {{ config('app.name') }} 14 | @endcomponent -------------------------------------------------------------------------------- /src/Http/VerifyNewEmailController.php: -------------------------------------------------------------------------------- 1 | middleware('throttle:6,1'); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /database/migrations/create_pending_user_emails_table.php.stub: -------------------------------------------------------------------------------- 1 | bigIncrements('id'); 18 | $table->morphs('user'); 19 | $table->string('email')->index(); 20 | $table->string('token'); 21 | $table->timestamp('created_at')->nullable(); 22 | }); 23 | } 24 | 25 | /** 26 | * Reverse the migrations. 27 | * 28 | * @return void 29 | */ 30 | public function down() 31 | { 32 | Schema::dropIfExists('pending_user_emails'); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /.phpunit.result.cache: -------------------------------------------------------------------------------- 1 | C:37:"PHPUnit\Runner\DefaultTestResultCache":1099:{a:2:{s:7:"defects";a:1:{s:89:"ProtoneMedia\LaravelVerifyNewEmail\Tests\VerifyNewEmailTest::it_can_generate_a_signed_url";i:4;}s:5:"times";a:7:{s:125:"ProtoneMedia\LaravelVerifyNewEmail\Tests\MustVerifyNewEmailTest::it_can_generate_a_token_and_mail_it_to_the_new_email_address";d:0.146;s:102:"ProtoneMedia\LaravelVerifyNewEmail\Tests\MustVerifyNewEmailTest::it_can_regenerate_a_token_and_mail_it";d:0.011;s:134:"ProtoneMedia\LaravelVerifyNewEmail\Tests\MustVerifyNewEmailTest::it_deletes_previous_attempts_of_the_user_trying_to_verify_a_new_email";d:0.01;s:126:"ProtoneMedia\LaravelVerifyNewEmail\Tests\VerifyNewEmailControllerTest::it_updates_the_user_email_and_deletes_the_pending_email";d:0.022;s:145:"ProtoneMedia\LaravelVerifyNewEmail\Tests\VerifyNewEmailControllerTest::it_removes_both_pending_models_if_two_users_try_to_verify_the_same_address";d:0.01;s:117:"ProtoneMedia\LaravelVerifyNewEmail\Tests\VerifyNewEmailControllerTest::it_throws_an_exception_if_the_token_is_invalid";d:0.012;s:89:"ProtoneMedia\LaravelVerifyNewEmail\Tests\VerifyNewEmailTest::it_can_generate_a_signed_url";d:0.086;}}} -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Pascal Baljet 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /src/Mail/VerifyNewEmail.php: -------------------------------------------------------------------------------- 1 | pendingUserEmail = $pendingUserEmail; 28 | } 29 | 30 | /** 31 | * Build the message. 32 | * 33 | * @return $this 34 | */ 35 | public function build() 36 | { 37 | $this->subject(__('Verify Email Address')); 38 | 39 | return $this->markdown('verify-new-email::verifyNewEmail', [ 40 | 'url' => $this->pendingUserEmail->verificationUrl(), 41 | ]); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/Mail/VerifyFirstEmail.php: -------------------------------------------------------------------------------- 1 | pendingUserEmail = $pendingUserEmail; 28 | } 29 | 30 | /** 31 | * Build the message. 32 | * 33 | * @return $this 34 | */ 35 | public function build() 36 | { 37 | $this->subject(__('Verify Email Address')); 38 | 39 | return $this->markdown('verify-new-email::verifyFirstEmail', [ 40 | 'url' => $this->pendingUserEmail->verificationUrl(), 41 | ]); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/Http/VerifiesPendingEmails.php: -------------------------------------------------------------------------------- 1 | whereToken($token)->firstOr(['*'], function () { 19 | throw new InvalidVerificationLinkException( 20 | __('The verification link is not valid anymore.') 21 | ); 22 | })->tap(function ($pendingUserEmail) { 23 | $pendingUserEmail->activate(); 24 | })->user; 25 | 26 | if (config('verify-new-email.login_after_verification')) { 27 | Auth::guard()->login($user, config('verify-new-email.login_remember')); 28 | } 29 | 30 | return $this->authenticated(); 31 | } 32 | 33 | protected function authenticated() 34 | { 35 | return redirect(config('verify-new-email.redirect_to'))->with('verified', true); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /config/config.php: -------------------------------------------------------------------------------- 1 | null, 8 | 9 | /** 10 | * Here you can specify the path to redirect to after verification. 11 | */ 12 | 'redirect_to' => '/home', 13 | 14 | /** 15 | * Whether to login the user after successfully verifying its email. 16 | */ 17 | 'login_after_verification' => true, 18 | 19 | /** 20 | * Should the user be permanently "remembered" by the application. 21 | */ 22 | 'login_remember' => false, 23 | 24 | /** 25 | * Model class that will be used to store and retrieve the tokens. 26 | */ 27 | 'model' => \ProtoneMedia\LaravelVerifyNewEmail\PendingUserEmail::class, 28 | 29 | /** 30 | * The Mailable that will be sent when the User wants to verify 31 | * its initial email address (that got used with registering). 32 | */ 33 | 'mailable_for_first_verification' => \ProtoneMedia\LaravelVerifyNewEmail\Mail\VerifyFirstEmail::class, 34 | 35 | /** 36 | * The Mailable that will be sent when the User wants to verify 37 | * a new email address, for example when the User wants to 38 | * update its email address. 39 | */ 40 | 'mailable_for_new_email' => \ProtoneMedia\LaravelVerifyNewEmail\Mail\VerifyNewEmail::class, 41 | ]; 42 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to `laravel-verify-new-email` will be documented in this file 4 | 5 | ## 1.6.0 - 2022-02-24 6 | 7 | - Interact with the Mailable before sending 8 | 9 | ## 1.5.0 - 2022-02-04 10 | 11 | - Support for Laravel 9 12 | 13 | ## 1.4.0 - 2021-12-19 14 | 15 | - Support for PHP 8.1 16 | - Dropped support for PHP 7.3 17 | - Dropped support for Laravel 6 and 7 18 | 19 | ## 1.3.1 - 2021-12-16 20 | 21 | - Redirect bugfix 22 | 23 | ## 1.3.0 - 2020-10-31 24 | 25 | - Support for PHP 8.0 26 | - Dropped support for PHP 7.2 27 | 28 | ## 1.2.1 - 2020-09-07 29 | 30 | - Added `InvalidEmailVerificationModelException` 31 | 32 | ## 1.2.0 - 2020-09-04 33 | 34 | - support for Laravel 8.0 35 | 36 | ## 1.1.0 - 2020-03-03 37 | 38 | - support for Laravel 7.0 39 | 40 | ## 1.0.7 - 2020-01-08 41 | 42 | - support for custom model 43 | - setting to remember login 44 | 45 | ## 1.0.6 - 2020-01-06 46 | 47 | - added `web` middleware to verification route 48 | 49 | ## 1.0.5 - 2020-01-05 50 | 51 | - don't fire event if nothing has changed 52 | - refactoring 53 | 54 | ## 1.0.4 - 2020-01-05 55 | 56 | - publishes the migration only once 57 | - refactoring 58 | 59 | ## 1.0.3 - 2020-01-01 60 | 61 | - added a subject to Mailables 62 | 63 | ## 1.0.2 - 2019-12-31 64 | 65 | - unguarded the PendingUserEmail model 66 | 67 | ## 1.0.1 - 2019-12-30 68 | 69 | - bugfix for sending the wrong Mailable 70 | 71 | ## 1.0.0 - 2019-12-30 72 | 73 | - initial release 74 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "protonemedia/laravel-verify-new-email", 3 | "description": "Package to handle email address updates and verification", 4 | "keywords": [ 5 | "protonemedia", 6 | "laravel-verify-new-email" 7 | ], 8 | "homepage": "https://github.com/protonemedia/laravel-verify-new-email", 9 | "license": "MIT", 10 | "type": "library", 11 | "authors": [ 12 | { 13 | "name": "Pascal Baljet", 14 | "email": "pascal@protone.media", 15 | "role": "Developer" 16 | } 17 | ], 18 | "require": { 19 | "php": "^8.2|^8.3|^8.4", 20 | "illuminate/support": "^10.0|^11.0|^12.0" 21 | }, 22 | "require-dev": { 23 | "orchestra/testbench": "^8.0|^9.0|^10.0", 24 | "phpunit/phpunit": "^10.4|^11.5.3" 25 | }, 26 | "autoload": { 27 | "psr-4": { 28 | "ProtoneMedia\\LaravelVerifyNewEmail\\": "src" 29 | } 30 | }, 31 | "autoload-dev": { 32 | "psr-4": { 33 | "ProtoneMedia\\LaravelVerifyNewEmail\\Tests\\": "tests" 34 | } 35 | }, 36 | "scripts": { 37 | "test": "vendor/bin/phpunit", 38 | "test-coverage": "vendor/bin/phpunit --coverage-html coverage" 39 | }, 40 | "config": { 41 | "sort-packages": true 42 | }, 43 | "minimum-stability": "dev", 44 | "prefer-stable": true, 45 | "extra": { 46 | "laravel": { 47 | "providers": [ 48 | "ProtoneMedia\\LaravelVerifyNewEmail\\ServiceProvider" 49 | ] 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /.github/workflows/run-tests.yml: -------------------------------------------------------------------------------- 1 | name: run-tests 2 | 3 | on: 4 | - push 5 | - pull_request 6 | 7 | jobs: 8 | test: 9 | runs-on: ubuntu-latest 10 | 11 | strategy: 12 | fail-fast: true 13 | matrix: 14 | php: [8.4, 8.3, 8.2] 15 | laravel: ["10.*", "11.*", "12.*"] 16 | dependency-version: [prefer-lowest, prefer-stable] 17 | include: 18 | - laravel: 10.* 19 | testbench: 8.* 20 | - laravel: 11.* 21 | testbench: 9.* 22 | - laravel: 12.* 23 | testbench: 10.* 24 | 25 | name: P${{ matrix.php }} - L${{ matrix.laravel }} - ${{ matrix.dependency-version }} 26 | 27 | steps: 28 | - name: Checkout code 29 | uses: actions/checkout@v4 30 | 31 | - name: Cache dependencies 32 | uses: actions/cache@v4 33 | with: 34 | path: ~/.composer/cache/files 35 | key: dependencies-laravel-${{ matrix.laravel }}-php-${{ matrix.php }}-composer-${{ hashFiles('composer.json') }} 36 | 37 | - name: Setup PHP 38 | uses: shivammathur/setup-php@v2 39 | with: 40 | php-version: ${{ matrix.php }} 41 | extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, sqlite, pdo_sqlite, bcmath, soap, intl, gd, exif, iconv, imagick, mysql, mysqli, pdo_mysql 42 | coverage: none 43 | 44 | - name: Install dependencies 45 | run: | 46 | composer require "laravel/framework:${{ matrix.laravel }}" "orchestra/testbench:${{ matrix.testbench }}" --no-interaction --no-update 47 | composer update --${{ matrix.dependency-version }} --prefer-dist --no-interaction --no-suggest 48 | 49 | - name: Execute tests 50 | run: vendor/bin/phpunit 51 | -------------------------------------------------------------------------------- /src/ServiceProvider.php: -------------------------------------------------------------------------------- 1 | loadViewsFrom(__DIR__ . '/../resources/views', 'verify-new-email'); 17 | 18 | if (!config('verify-new-email.route')) { 19 | $this->loadRoutesFrom(__DIR__ . '/routes.php'); 20 | } 21 | 22 | if ($this->app->runningInConsole()) { 23 | $this->publishes([ 24 | __DIR__ . '/../database/migrations/create_pending_user_emails_table.php.stub' => $this->getMigrationFileName($filesystem), 25 | ], 'migrations'); 26 | 27 | $this->publishes([ 28 | __DIR__ . '/../config/config.php' => config_path('verify-new-email.php'), 29 | ], 'config'); 30 | 31 | $this->publishes([ 32 | __DIR__ . '/../resources/views' => resource_path('views/vendor/verify-new-email'), 33 | ], 'views'); 34 | 35 | // $this->commands([]); 36 | } 37 | } 38 | 39 | /** 40 | * Returns existing migration file if found, else uses the current timestamp. 41 | * 42 | * @param Filesystem $filesystem 43 | * @return string 44 | */ 45 | protected function getMigrationFileName(Filesystem $filesystem): string 46 | { 47 | $timestamp = date('Y_m_d_His'); 48 | 49 | return Collection::make($this->app->databasePath('migrations') . DIRECTORY_SEPARATOR) 50 | ->flatMap(function ($path) use ($filesystem) { 51 | return $filesystem->glob("{$path}*_create_pending_user_emails_table.php"); 52 | }) 53 | ->push($this->app->databasePath("migrations/{$timestamp}_create_pending_user_emails_table.php")) 54 | ->first(); 55 | } 56 | 57 | /** 58 | * Register the application services. 59 | */ 60 | public function register() 61 | { 62 | $this->mergeConfigFrom(__DIR__ . '/../config/config.php', 'verify-new-email'); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/PendingUserEmail.php: -------------------------------------------------------------------------------- 1 | morphTo('user'); 33 | } 34 | 35 | /** 36 | * Scope for the user. 37 | * 38 | * @param $query 39 | * @param \Illuminate\Database\Eloquent\Model $user 40 | * @return void 41 | */ 42 | public function scopeForUser($query, Model $user) 43 | { 44 | $query->where([ 45 | $this->qualifyColumn('user_type') => get_class($user), 46 | $this->qualifyColumn('user_id') => $user->getKey(), 47 | ]); 48 | } 49 | 50 | /** 51 | * Updates the associated user and removes all pending models with this email. 52 | * 53 | * @return void 54 | */ 55 | public function activate() 56 | { 57 | $user = $this->user; 58 | 59 | $dispatchEvent = !$user->hasVerifiedEmail() || $user->email !== $this->email; 60 | 61 | $user->email = $this->email; 62 | $user->save(); 63 | $user->markEmailAsVerified(); 64 | 65 | static::whereEmail($this->email)->get()->each->delete(); 66 | 67 | $dispatchEvent ? event(new Verified($user)) : null; 68 | } 69 | 70 | /** 71 | * Creates a temporary signed URL to verify the pending email. 72 | * 73 | * @return string 74 | */ 75 | public function verificationUrl(): string 76 | { 77 | return URL::temporarySignedRoute( 78 | config('verify-new-email.route') ?: 'pendingEmail.verify', 79 | now()->addMinutes(config('auth.verification.expire', 60)), 80 | ['token' => $this->token] 81 | ); 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Contributions are **welcome** and will be fully **credited**. 4 | 5 | Please read and understand the contribution guide before creating an issue or pull request. 6 | 7 | ## Etiquette 8 | 9 | This project is open source, and as such, the maintainers give their free time to build and maintain the source code 10 | held within. They make the code freely available in the hope that it will be of use to other developers. It would be 11 | extremely unfair for them to suffer abuse or anger for their hard work. 12 | 13 | Please be considerate towards maintainers when raising issues or presenting pull requests. Let's show the 14 | world that developers are civilized and selfless people. 15 | 16 | It's the duty of the maintainer to ensure that all submissions to the project are of sufficient 17 | quality to benefit the project. Many developers have different skillsets, strengths, and weaknesses. Respect the maintainer's decision, and do not be upset or abusive if your submission is not used. 18 | 19 | ## Viability 20 | 21 | When requesting or submitting new features, first consider whether it might be useful to others. Open 22 | source projects are used by many developers, who may have entirely different needs to your own. Think about 23 | whether or not your feature is likely to be used by other users of the project. 24 | 25 | ## Procedure 26 | 27 | Before filing an issue: 28 | 29 | - Attempt to replicate the problem, to ensure that it wasn't a coincidental incident. 30 | - Check to make sure your feature suggestion isn't already present within the project. 31 | - Check the pull requests tab to ensure that the bug doesn't have a fix in progress. 32 | - Check the pull requests tab to ensure that the feature isn't already in progress. 33 | 34 | Before submitting a pull request: 35 | 36 | - Check the codebase to ensure that your feature doesn't already exist. 37 | - Check the pull requests to ensure that another person hasn't already submitted the feature or fix. 38 | 39 | ## Requirements 40 | 41 | If the project maintainer has any additional requirements, you will find them listed here. 42 | 43 | - **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](https://pear.php.net/package/PHP_CodeSniffer). 44 | 45 | - **Add tests!** - Your patch won't be accepted if it doesn't have tests. 46 | 47 | - **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date. 48 | 49 | - **Consider our release cycle** - We try to follow [SemVer v2.0.0](https://semver.org/). Randomly breaking public APIs is not an option. 50 | 51 | - **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. 52 | 53 | - **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](https://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting. 54 | 55 | **Happy coding**! 56 | -------------------------------------------------------------------------------- /src/MustVerifyNewEmail.php: -------------------------------------------------------------------------------- 1 | getEmailForVerification() === $email && $this->hasVerifiedEmail()) { 23 | return null; 24 | } 25 | 26 | return $this->createPendingUserEmailModel($email)->tap(function ($model) use ($withMailable) { 27 | $this->sendPendingEmailVerificationMail($model, $withMailable); 28 | }); 29 | } 30 | 31 | public function getEmailVerificationModel(): Model 32 | { 33 | $modelClass = config('verify-new-email.model'); 34 | 35 | if (!$modelClass) { 36 | throw new InvalidEmailVerificationModelException; 37 | } 38 | 39 | return app($modelClass); 40 | } 41 | 42 | /** 43 | * Creates new PendingUserModel model for the given email. 44 | * 45 | * @param string $email 46 | * @return \Illuminate\Database\Eloquent\Model 47 | */ 48 | public function createPendingUserEmailModel(string $email): Model 49 | { 50 | $this->clearPendingEmail(); 51 | 52 | return $this->getEmailVerificationModel()->create([ 53 | 'user_type' => get_class($this), 54 | 'user_id' => $this->getKey(), 55 | 'email' => $email, 56 | 'token' => Password::broker()->getRepository()->createNewToken(), 57 | ]); 58 | } 59 | 60 | /** 61 | * Returns the pending email address. 62 | * 63 | * @return string|null 64 | */ 65 | public function getPendingEmail(): ?string 66 | { 67 | return $this->getEmailVerificationModel()->forUser($this)->value('email'); 68 | } 69 | 70 | /** 71 | * Deletes the pending email address models for this user. 72 | * 73 | * @return void 74 | */ 75 | public function clearPendingEmail() 76 | { 77 | $this->getEmailVerificationModel()->forUser($this)->get()->each->delete(); 78 | } 79 | 80 | /** 81 | * Sends the VerifyNewEmail Mailable to the new email address. 82 | * 83 | * @param \Illuminate\Database\Eloquent\Model $pendingUserEmail 84 | * @param callable|null $withMailable 85 | * @return mixed 86 | */ 87 | public function sendPendingEmailVerificationMail(Model $pendingUserEmail, ?callable $withMailable = null) 88 | { 89 | $mailableClass = config('verify-new-email.mailable_for_first_verification'); 90 | 91 | if ($pendingUserEmail->User->hasVerifiedEmail()) { 92 | $mailableClass = config('verify-new-email.mailable_for_new_email'); 93 | } 94 | 95 | $mailable = new $mailableClass($pendingUserEmail); 96 | 97 | if ($withMailable) { 98 | $withMailable($mailable, $pendingUserEmail); 99 | } 100 | 101 | return Mail::to($pendingUserEmail->email)->send($mailable); 102 | } 103 | 104 | /** 105 | * Grabs the pending user email address, generates a new token and sends the Mailable. 106 | * 107 | * @return \Illuminate\Database\Eloquent\Model|null 108 | */ 109 | public function resendPendingEmailVerificationMail(): ?Model 110 | { 111 | $pendingUserEmail = $this->getEmailVerificationModel()->forUser($this)->firstOrFail(); 112 | 113 | return $this->newEmail($pendingUserEmail->email); 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Laravel Verify New Email 2 | 3 | [![Latest Version on Packagist](https://img.shields.io/packagist/v/protonemedia/laravel-verify-new-email.svg?style=flat-square)](https://packagist.org/packages/protonemedia/laravel-verify-new-email) 4 | ![run-tests](https://github.com/protonemedia/laravel-verify-new-email/workflows/run-tests/badge.svg) 5 | [![Quality Score](https://img.shields.io/scrutinizer/g/protonemedia/laravel-verify-new-email.svg?style=flat-square)](https://scrutinizer-ci.com/g/protonemedia/laravel-verify-new-email) 6 | [![Total Downloads](https://img.shields.io/packagist/dt/protonemedia/laravel-verify-new-email.svg?style=flat-square)](https://packagist.org/packages/protonemedia/laravel-verify-new-email) 7 | 8 | 9 | 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 9.0 and higher and requires PHP 8.2 or higher. 10 | 11 | ## Sponsor Us 12 | 13 | [](https://inertiaui.com/inertia-table?utm_source=github&utm_campaign=laravel-verify-new-email) 14 | 15 | ❤️ We proudly support the community by developing Laravel packages and giving them away for free. If this package saves you time or if you're relying on it professionally, please consider [sponsoring the maintenance and development](https://github.com/sponsors/pascalbaljet) and check out our latest premium package: [Inertia Table](https://inertiaui.com/inertia-table?utm_source=github&utm_campaign=laravel-verify-new-email). Keeping track of issues and pull requests takes time, but we're happy to help! 16 | 17 | ## Blogpost 18 | 19 | If you want to know more about the background of this package, please read [the blog post](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). 20 | 21 | ## Requirements 22 | 23 | * PHP 8.2 or higher 24 | * Laravel 10 or higher 25 | 26 | ## Installation 27 | 28 | You can install the package via composer: 29 | 30 | ```bash 31 | composer require protonemedia/laravel-verify-new-email 32 | ``` 33 | 34 | ## Configuration 35 | 36 | Publish the database migration, config file and email view: 37 | 38 | ```bash 39 | php artisan vendor:publish --provider="ProtoneMedia\LaravelVerifyNewEmail\ServiceProvider" 40 | ``` 41 | 42 | You can set the redirect path in the `verify-new-email.php` config file. The user will be redirected to this path after verification. 43 | 44 | The expire time of the verification URLs can be changed by updating the `auth.verification.expire` setting and defaults to 60 minutes. 45 | 46 | ## Usage 47 | 48 | Add the `MustVerifyNewEmail` trait to your `User` model and make sure it implements the framework's `MustVerifyEmail` interface as well. 49 | 50 | ``` php 51 | newEmail('me@newcompany.com'); 71 | 72 | // returns the currently pending email address that needs to be verified. 73 | $user->getPendingEmail(); 74 | 75 | // resends the verification mail for 'me@newcompany.com'. 76 | $user->resendPendingEmailVerificationMail(); 77 | 78 | // deletes the pending email address 79 | $user->clearPendingEmail(); 80 | ``` 81 | 82 | 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. 83 | 84 | The `resendPendingEmailVerificationMail` does the same, it just grabs the new email address from the previous attempt. 85 | 86 | ### Login after verification 87 | 88 | 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`. 89 | 90 | ### Overriding the default Laravel Email Verification 91 | 92 | The default [Laravel implementation](https://laravel.com/docs/master/verification) 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. 93 | 94 | ``` php 95 | newEmail($this->getEmailForVerification()); 111 | } 112 | } 113 | ``` 114 | 115 | ### Customization 116 | 117 | 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: 118 | 119 | ``` php 120 | \ProtoneMedia\LaravelVerifyNewEmail\Mail\VerifyFirstEmail::class, 125 | 126 | 'mailable_for_new_email' => \ProtoneMedia\LaravelVerifyNewEmail\Mail\VerifyNewEmail::class, 127 | 128 | ]; 129 | ``` 130 | 131 | You can also override the `sendPendingEmailVerificationMail` method to change the behaviour of sending the verification mail: 132 | 133 | ``` php 134 | 'user.email.verify', 163 | 164 | ]; 165 | 166 | ``` 167 | 168 | ### Testing 169 | 170 | ``` bash 171 | composer test 172 | ``` 173 | 174 | ### Changelog 175 | 176 | Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently. 177 | 178 | ## Contributing 179 | 180 | Please see [CONTRIBUTING](CONTRIBUTING.md) for details. 181 | 182 | ## Other Laravel packages 183 | 184 | * [`Inertia Table`](https://inertiaui.com/inertia-table?utm_source=github&utm_campaign=laravel-verify-new-email): The Ultimate Table for Inertia.js with built-in Query Builder. 185 | * [`Laravel Blade On Demand`](https://github.com/protonemedia/laravel-blade-on-demand): Laravel package to compile Blade templates in memory. 186 | * [`Laravel Cross Eloquent Search`](https://github.com/protonemedia/laravel-cross-eloquent-search): Laravel package to search through multiple Eloquent models. 187 | * [`Laravel Eloquent Scope as Select`](https://github.com/protonemedia/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. 188 | * [`Laravel FFMpeg`](https://github.com/protonemedia/laravel-ffmpeg): This package provides an integration with FFmpeg for Laravel. The storage of the files is handled by Laravel's Filesystem. 189 | * [`Laravel MinIO Testing Tools`](https://github.com/protonemedia/laravel-minio-testing-tools): Run your tests against a MinIO S3 server. 190 | * [`Laravel Mixins`](https://github.com/protonemedia/laravel-mixins): A collection of Laravel goodies. 191 | * [`Laravel Paddle`](https://github.com/protonemedia/laravel-paddle): Paddle.com API integration for Laravel with support for webhooks/events. 192 | * [`Laravel Task Runner`](https://github.com/protonemedia/laravel-task-runner): Write Shell scripts like Blade Components and run them locally or on a remote server. 193 | * [`Laravel XSS Protection`](https://github.com/protonemedia/laravel-xss-protection): Laravel Middleware to protect your app against Cross-site scripting (XSS). It sanitizes request input, and it can sanatize Blade echo statements. 194 | 195 | ### Security 196 | 197 | If you discover any security-related issues, please email pascal@protone.media instead of using the issue tracker. 198 | 199 | ## Credits 200 | 201 | - [Pascal Baljet](https://github.com/pascalbaljetmedia) 202 | - [All Contributors](../../contributors) 203 | 204 | ## License 205 | 206 | The MIT License (MIT). Please see [License File](LICENSE.md) for more information. 207 | --------------------------------------------------------------------------------