我想创建一个Laravel注册系统,我会在用户注册后发送电子邮件来验证电子邮件。我尝试添加一个分派给创建的方法的事件,但是我收到了一个错误
Fatal error: Non-static method Illuminate\Contracts\Events\Dispatcher::fire() cannot be called statically
这是我想出的。
<?php
namespace App;
use Laravel\Cashier\Billable;
use Laravel\Spark\Teams\CanJoinTeams;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as BaseUser;
use Laravel\Spark\Auth\TwoFactor\Authenticatable as TwoFactorAuthenticatable;
use Illuminate\Contracts\Events\Dispatcher as EventDispatcher;
use Laravel\Spark\Contracts\Auth\TwoFactor\Authenticatable as TwoFactorAuthenticatableContract;
class User extends BaseUser implements TwoFactorAuthenticatableContract
{
use Billable, TwoFactorAuthenticatable,CanJoinTeams;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'email',
'name',
'password',
];
/**
* The accessors to append to the model's array form.
*
* @var array
*/
protected $appends = [
];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = [
'card_brand',
'card_last_four',
'extra_billing_info',
'password',
'remember_token',
'stripe_id',
'stripe_subscription'
];
/**
* Boot the model.
*
* @return void
*/
public static function boot()
{
parent::boot();
static::creating(function ($user) {
$user->token = str_random(30);
});
static::created(function ( $user) {
EventDispatcher::fire('UserCreated');
});
}
/**
* Confirm the user.
*
* @return void
*/
public function confirmEmail()
{
$this->verified = true;
$this->token = null;
$this->save();
}
}
我也尝试将代码更改为
use Billable, TwoFactorAuthenticatable,CanJoinTeams, EventDispatcher;
并用
替换引导部分 static::created(function ( $user, EventDispatcher $event) {
$event->fire('UserCreated');
});
但它给了我另一个错误
App\User cannot use Illuminate\Contracts\Events\Dispatcher - it is not a trait
创建模型后如何触发事件?
答案 0 :(得分:1)
模型的生命周期事件已经被Eloquent解雇了,所以不需要自己解雇它们。使用以下代码创建事件名称:
$event = "eloquent.{$event}: ".get_class($model);
因此,如果您想要收听已创建的事件,则需要收听&#34; eloquent.created:App \ User&#34; 。事件处理程序将相关的用户模型作为 handle()参数之一。
如果您希望发送自己的活动,可以使用活动立面来实现:
Event::fire('UserCreated', $user);
您可以在此处阅读有关Laravel活动的更多信息:https://laravel.com/docs/5.1/events
答案 1 :(得分:0)
在Laravel> 5.4
及更高版本中,您可以在Model类中关联雄辩的事件以触发自定义事件-例如'created' => ProjectCreated::class
。因此,基本上,在雄辩的模型created
上触发ProjectCreated
事件。
class Project extends Model
{
/**
* @var array
*/
protected $fillable = ['title', 'description', 'client_id'];
/**
*
* Eloquent model events
*
* @var array
*/
protected $dispatchesEvents = [
'created' => ProjectCreated::class,
];
}