【原创】Laravel 邮件发送

增加激活相关的用户表字段

php artisan make:migration add_activation_to_users_table --table=users

database/migrations/[timestamp]_add_activation_to_users_table.php

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('activation_token')->nullable();
            $table->boolean('activated')->default(false);
        });
    }

    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('activation_token');
            $table->dropColumn('activated');
        });
    }
};

php artisan migrate

生成令牌

令牌是要在用户被创建之前生成,在模型中使用 creating 方法来监听模型被创建之前要进行的动作,而如果要在模型创建之后进行设置,则使用 created 方法。

app/Models/User.php

<?php

namespace App\Models;

use Illuminate\Support\Str;

class User extends Authenticatable
{
    protected $hidden = [
        'password', 'remember_token',
    ];

    public static function boot()
    {
        parent::boot();

        static::creating(function ($user) {
            $user->activation_token = Str::random(10);
        });
    }
}

boot 方法会在用户模型类完成初始化之后进行加载。

更新模型工厂,将生成用户的激活状态设置为 true:

<?php

namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;

class UserFactory extends Factory
{
    public function definition()
    {
        return [
            'name' => $this->faker->name,
            'email' => $this->faker->unique()->safeEmail,
            'email_verified_at' => now(),
            'activated' => true,
            'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
            'remember_token' => Str::random(10),
        ];
    }

    public function unverified()
    {
        return $this->state(function (array $attributes) {
            return [
                'email_verified_at' => null,
            ];
        });
    }
}
php artisan migrate:refresh --seed

发送邮件

在 Laravel 中,可以通过 Mail 接口中的 send 方法来发送邮件,代码如下:

$view = 'emails.confirm';
$data = compact('user');
$from = 'star@example.com';
$name = 'Star';
$to = $user->email;
$subject = "感谢注册 Weibo 应用!请确认你的邮箱。";

Mail::send($view, $data, function ($message) use ($from, $name, $to, $subject) {
    $message->from($from, $name)->to($to)->subject($subject);
});

Mailsend 方法接收三个参数:

  • 第一个是视图名称
  • 第二个是要传给视图的数组
  • 第三个是接收邮件消息实例的闭包回调,可以在该回调中定义消息的发送者、接收者、邮件主题等信息

激活功能

<?php

namespace App\Http\Controllers;.

class UsersController extends Controller
{
    public function __construct()
    {

        $this->middleware('auth', [
            'except' => ['show', 'create', 'store', 'index', 'confirmEmail']
        ]);
    }

    public function confirmEmail($token)
    {
        $user = User::where('activation_token', $token)->firstOrFail();

        $user->activated = true;
        $user->activation_token = null;
        $user->save();

        Auth::login($user);
        session()->flash('success', '恭喜你,激活成功!');
        return redirect()->route('users.show', [$user]);
    }
}
点赞

发表回复

电子邮件地址不会被公开。必填项已用 * 标注