plin-code/laravel-email-fixer 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

plin-code/laravel-email-fixer

Composer 安装命令:

composer require plin-code/laravel-email-fixer

包简介

Sanitize, normalize and auto-correct malformed email addresses before validation in Laravel

README 文档

README

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

Sanitize, normalize and auto-correct malformed email addresses in Laravel. Handles common typos from web forms, CSV imports, and mobile keyboards, including locale-specific issues like the Italian ò@ keyboard quirk.

The Problem

Users constantly submit broken email addresses. Typos, missing @ signs, incomplete domains, trailing dots, angle brackets from copy-paste, commas instead of dots. Every registration form, every CSV import, every contact form collects these. Most apps just reject them and lose the user.

Laravel Email Fixer automatically repairs these emails before validation, so your users don't bounce off your forms.

What It Fixes

Input Output Fixer
user@gmail.com user@gmail.com TrimWhitespace
<user@gmail.com> user@gmail.com StripAngleBrackets
user@gmail,com user@gmail.com CommaToDot
usergmail.com user@gmail.com InsertMissingAt
user@gmail user@gmail.com CompleteDomain
user@gmailcom user@gmail.com FixDomainSeparator
user.@gmail.com user@gmail.com CleanLocalPart
user@gmail.com. user@gmail.com CleanTrailingDots
User@Gmail.COM user@gmail.com Lowercase
user@gmail.com§ user@gmail.com StripNonAsciiTrailing
userògmail.com user@gmail.com ItalianKeyboard (locale: it)

Installation

composer require plin-code/laravel-email-fixer

Optionally publish the config file:

php artisan vendor:publish --tag="laravel-email-fixer-config"

Quick Start

Using the Facade

use PlinCode\LaravelEmailFixer\Facades\EmailFixer;

// Fix a single email
$fixed = EmailFixer::fix('user@gmail,com');
// "user@gmail.com"

// Fix or get null if unfixable
$fixed = EmailFixer::fixOrNull('not-an-email');
// null

// Check if input is garbage before attempting a fix
$isGarbage = EmailFixer::isGarbage('asdf');
// true

// Get a detailed report
$report = EmailFixer::diagnose('usergmail.com');
// $report->original       → "usergmail.com"
// $report->fixed          → "user@gmail.com"
// $report->appliedFixers  → ["InsertMissingAt"]
// $report->isValid        → true
// $report->wasModified    → true

// Batch processing
$reports = EmailFixer::fixMany([
    'user@gmail,com',
    'admin@yahoo',
    'info@hotmail.com.',
]);

Using the Validation Rule

Apply the SanitizedEmail rule to auto-fix and validate email fields in one step. The fixed value is automatically merged back into the request.

use PlinCode\LaravelEmailFixer\Rules\SanitizedEmail;

public function rules(): array
{
    return [
        'email' => ['required', new SanitizedEmail],
    ];
}

With options:

// Enable strict RFC validation and garbage rejection
new SanitizedEmail(strict: true, rejectGarbage: true)

// With Italian locale
new SanitizedEmail(locale: 'it')

Using the Middleware

Register the SanitizeEmails middleware to automatically fix all email fields in incoming requests before they reach your controllers.

use PlinCode\LaravelEmailFixer\Middleware\SanitizeEmails;

// In a route group
Route::middleware(SanitizeEmails::class)->group(function () {
    Route::post('/register', [RegisterController::class, 'store']);
});

// Or globally in bootstrap/app.php
->withMiddleware(function (Middleware $middleware) {
    $middleware->append(SanitizeEmails::class);
})

By default, the middleware targets fields matching these patterns: email, *_email, email_*, *email*. You can customize this in the config file.

Use Cases

Registration and Login Forms

The most common scenario. Users mistype their email on signup, never receive the confirmation, and leave. With Email Fixer, most typos are silently corrected.

// In your registration form request
public function rules(): array
{
    return [
        'email' => ['required', new SanitizedEmail(rejectGarbage: true), 'unique:users'],
    ];
}

CSV/Bulk Import

When importing contacts or users from spreadsheets, email quality is often poor. Use fixMany() to clean them in bulk and diagnose() to flag the ones that could not be repaired.

use PlinCode\LaravelEmailFixer\Facades\EmailFixer;

$emails = array_column($rows, 'email');

$reports = EmailFixer::fixMany($emails);

foreach ($reports as $index => $report) {
    if ($report->isValid) {
        $rows[$index]['email'] = $report->fixed;
    } else {
        $failed[] = $rows[$index]; // flag for manual review
    }
}

Italian (or Locale-Specific) Users

Italian keyboards place the ò key right next to the @ key, causing a very common typo. Enable the Italian locale to handle this automatically, along with local domain shortcuts like liberolibero.it.

// Via config (config/email-fixer.php)
'locale' => 'it',

// Or at runtime
$fixer = EmailFixer::locale('it');
$fixer->fix('mrossiòlibero'); // "mrossi@libero.it"

API Input Sanitization

Use the middleware on your API routes to transparently sanitize emails before any validation or processing takes place.

Route::middleware(SanitizeEmails::class)
    ->prefix('api')
    ->group(function () {
        Route::post('/subscribe', [NewsletterController::class, 'subscribe']);
        Route::post('/invite', [InviteController::class, 'send']);
    });

Auditing and Debugging

Use diagnose() to understand exactly what was changed and why, useful for logging or admin dashboards.

$report = EmailFixer::diagnose('  USER@Gmail,COM.  ');

logger()->info('Email fixed', [
    'original' => $report->original,
    'fixed' => $report->fixed,
    'fixers' => $report->appliedFixers,
    'was_modified' => $report->wasModified,
]);

Configuration

The published config file (config/email-fixer.php) allows you to customize:

return [
    // Locale preset: 'it' or null
    'locale' => null,

    // Domain shortcuts (expanded by CompleteDomain fixer)
    'domains' => [
        'gmail'       => 'gmail.com',
        'hotmail'     => 'hotmail.com',
        'yahoo'       => 'yahoo.com',
        'outlook'     => 'outlook.com',
        'icloud'      => 'icloud.com',
        'live'        => 'live.com',
        'proton'      => 'proton.me',
        'protonmail'  => 'protonmail.com',
    ],

    // Custom fixer pipeline (null = default pipeline)
    'fixers' => null,

    // Middleware field patterns
    'middleware' => [
        'fields' => ['email', '*_email', 'email_*', '*email*'],
    ],

    // Garbage detection thresholds
    'garbage' => [
        'min_length' => 3,
        'require_at' => true,
        'require_dot_in_domain' => true,
    ],
];

Custom Fixer Pipeline

You can define your own fixer order or add custom fixers:

'fixers' => [
    \PlinCode\LaravelEmailFixer\Fixers\TrimWhitespace::class,
    \PlinCode\LaravelEmailFixer\Fixers\Lowercase::class,
    \App\EmailFixers\MyCustomFixer::class,
],

Custom fixers must implement PlinCode\LaravelEmailFixer\Contracts\FixerInterface:

use PlinCode\LaravelEmailFixer\Contracts\FixerInterface;

class MyCustomFixer implements FixerInterface
{
    public function fix(string $email): string
    {
        // your logic here
        return $email;
    }

    public function name(): string
    {
        return 'MyCustomFixer';
    }
}

Standalone Usage

You can use Email Fixer outside of Laravel:

use PlinCode\LaravelEmailFixer\EmailFixer;

$fixer = EmailFixer::defaults(
    domainMap: ['gmail' => 'gmail.com', 'yahoo' => 'yahoo.com'],
);

$fixed = $fixer->fix('user@gmail');
// "user@gmail.com"

Testing

composer test

Changelog

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

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

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

plin-code/laravel-email-fixer 适用场景与选型建议

plin-code/laravel-email-fixer 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 315 次下载、GitHub Stars 达 5, 最近一次更新时间为 2026 年 03 月 28 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「email」 「validation」 「laravel」 「sanitize」 「normalize」 「typo」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 plin-code/laravel-email-fixer 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 plin-code/laravel-email-fixer 我们能提供哪些服务?
定制开发 / 二次开发

基于 plin-code/laravel-email-fixer 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 315
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 5
  • 点击次数: 41
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 5
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2026-03-28