05.注册用户同时创建用户的频道

1.完善频道表

public function up()
{
    Schema::create('channels', function (Blueprint $table) {
        $table->uuid('id');
        $table->string('name');
        $table->uuid('user_id');
        $table->text('description')->nullable();
        $table->string('image')->nullable();
        $table->timestamps();
    });
}

并迁移

php artisan migrate:refresh

2.创建监听器

E:\phpstudy_pro\WWW\tube>php artisan make:listener Users/CreateUserChannel
Listener created successfully.

3.关联监听器与事件

protected $listen = [
    Registered::class => [
        SendEmailVerificationNotification::class,
        CreateUserChannel::class
    ],
];

4.CreateUserChannel.php中添加如下代码

public function handle($event)
{
    $event->user->channel()->create([
        'name'=>$event->user->name,
    ]);
}

5.User模型和Channel模型中分别添加如下代码

//User.php
public function channel(){
    return $this->hasOne(Channel::class);
}
//Channel.php
public function user(){
    return $this->belongsTo(User::class);
}

王如棋博客
请先登录后发表评论
  • 最新评论
  • 总共0条评论