php - 在观察者中聆听 Eloquent 模型事件

标签 php laravel laravel-4

我无法在我的事件处理程序中找到用于监听 eloquent 事件的语法。

我这样订阅了我的观察者

Event::subscribe('Animekyun\Handlers\Events\EloquentEventHandler');

这个观察者是 self 处理的,是这样实现的:

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');
    }

}

我不知道如何听这种形式的任何 Eloquent 事件。我确信有一种方法可以在不执行以下操作的情况下收听事件:

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)。

关于php - 在观察者中聆听 Eloquent 模型事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30140881/

相关文章:

php - 如何通过POST类型以html形式发送PHP数组

php - Laravel Eloquent 查询哪里喜欢关系?

php - Laravel Eloquent 加入

php - 将 echo 和 print 组合在一个语句中

用于合并单元格的 PHPExcel setAutoSize

laravel - 在 Laravel 的 Blade 模板中显示格式化属性

php - 无重复日期

php - 为 Laravel 中的每个 Controller 和方法创建一个路由

javascript - 在 Laravel 中从 JavaScript 调用模型函数

php - 如何创建菜单?