![](/img/trans.png)
[英]Can Eloquent model observer access model data that are being affected by the event?
[英]Listen to eloquent model event in an observer
我找不到在事件处理程序中侦听雄辩事件的语法。
我像这样订阅了我的观察者
Event::subscribe('Animekyun\Handlers\Events\EloquentEventHandler');
该观察者是自我处理的,实现方式如下:
namespace Animekyun\Handlers\Events;
use Illuminate\Events\Dispatcher;
class EloquentEventHandler
{
public function onEpisodeSave($event) {
dd('test');
}
public function subscribe(Dispatcher $events)
{
$events->listen('eloquent.saved: episode', 'Animekyun\Handlers\Events\EloquentEventHandler@onEpisodeSave');
}
}
我不知道该如何聆听任何雄辩的事件。 我确定有一种无需做类似事情就可以监听事件的方法:
User::creating(function($user)
{
if ( ! $user->isValid()) return false;
});
编辑:用户模型
<?php
use Laracasts\Presenter\PresentableTrait;
use Conner\Likeable\LikeableTrait;
class Episode extends \Eloquent
{
use PresentableTrait;
use LikeableTrait;
public static $rules = [
'show_id' => 'required',
'episode_number' => 'required',
];
// Add your validation rules here
protected $presenter = 'Animekyun\Presenters\EpisodePresenter';
// Don't forget to fill this array
protected $fillable = ['title', 'body', 'links', 'show_id', 'episode_number', 'format_id', 'created_by', 'updated_by', 'screenshots'];
public function scopeSearch($query, $search)
{
return $search;
}
public function user()
{
return $this->belongsTo('User', 'created_by');
}
public function show()
{
return $this->belongsTo('Show');
}
public function format()
{
return $this->belongsTo('Format');
}
public function rating()
{
return $this->morphMany('Rating', 'rateable');
}
public function getLinksAttribute()
{
return (array) json_decode($this->attributes['links'], true);
}
public function setLinksAttribute($value)
{
$this->attributes['links'] = json_encode($value);
}
}
有任何想法吗?
您正在听错事件。 因为字符串比较区分大小写,所以您应该侦听eloquent.saved: Episode
事件。 注意Episode
上的大写E
触发事件后,类名不会转换为小写。
另外,虽然这不适用于您的特定情况,但应注意,如果类是在名称空间下定义的,例如App
,则还需要包括该名称空间(即App\\Episode
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.