如果您想创建一个Laravel 7 应用程序,允许用户在您的应用程序上注册和登录,并且您打算使每个用户能够通过您的平台发送电子邮件,使用他们自己的唯一电子邮件地址和密码.
解决方案:
- Laravel Model:首先您需要创建一个数据库表来存储用户的电子邮件配置数据。接下来,您需要一个 Eloquent 模型 来检索经过身份验证的用户的 id 以动态获取他们的电子邮件配置数据。
- Laravel ServiceProvider:接下来,创建一个服务提供者,它将使用 Model 类中的范围方法查询数据库以获取用户的电子邮件配置,并将其设置为他们的默认邮件配置。不要在您的
config/app.php 中注册此服务提供商
- Laravel MiddleWare:还创建一个中间件,在用户通过身份验证并注册 ServiceProvider 时运行。
实现模型:
进行迁移。从命令行php artisan make:migration create_user_email_configurations_table 运行这些。那么:
Schema::create('user_email_configurations', function (Blueprint $table) {
$table->id();
$table->string('user_id');
$table->string('name');
$table->string('address');
$table->string('driver');
$table->string('host');
$table->string('port');
$table->string('encryption');
$table->string('username');
$table->string('password');
$table->timestamps();
});
完成并创建您的模型。运行php artisan migrate 和
php artisan make:model userEmailConfiguration。现在在你的模型中添加一个作用域方法。
<?php
namespace App;
use Illuminate\Support\Facades\Auth;
use Illuminate\Database\Eloquent\Model;
class userEmailConfiguration extends Model
{
protected $hidden = [
'driver',
'host',
'port',
'encryption',
'username',
'password'
];
public function scopeConfiguredEmail($query) {
$user = Auth::user();
return $query->where('user_id', $user->id);
}
}
实施服务提供者
从命令行运行它 - php artisan make:provider MailServiceProvider
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\userEmailConfiguration;
use Config;
class MailServiceProvider extends ServiceProvider
{
public function register()
{
$mail = userEmailConfiguration::configuredEmail()->first();
if (isset($mail->id))
{
$config = array(
'driver' => $mail->driver,
'host' => $mail->host,
'port' => $mail->port,
'from' => array('address' => $mail->address, 'name' => $mail->name),
'encryption' => $mail->encryption,
'username' => $mail->username,
'password' => $mail->password
);
Config::set('mail', $config);
}
}
public function boot()
{
}
}
实现中间件
运行以下命令 - php artisan make:middleware MailService
<?php
namespace App\Http\Middleware;
use Closure;
use App;
class MailService
{
public function handle($request, Closure $next)
{
$app = App::getInstance();
$app->register('App\Providers\MailServiceProvider');
return $next($request);
}
}
现在我们已经实现了所有这些,在 $routedMiddleware 数组中的 kennel.php 中将中间件注册为 mail。然后在经过身份验证的路由中间件中调用它:
示例:
Route::group(['middleware' => [ 'auth:api' ]], function () {
Route::post('send/email', 'Controller@test_mail')->middleware('mail');
});
这是我在媒体上发布的原始帖子 -
Enable Unique And Dynamic SMTP Mail Settings For Each User — Laravel 7