【问题标题】:Listen to eloquent model event in an observer在观察者中收听雄辩的模型事件
【发布时间】:2015-05-12 04:42:41
【问题描述】:

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

我像这样订阅了我的观察者

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

有什么想法吗?

【问题讨论】:

  • episode 类是如何定义的?
  • 像任何其他模型一样。它扩展了Eloquent 类并具有一些关系方法。没有什么不寻常的
  • 你能编辑问题并添加类声明吗?我的猜测是它不起作用,因为命名空间和可能区分大小写。
  • @KemalFadillah 已更新

标签: php laravel laravel-4


【解决方案1】:

您正在收听错误的事件。因为字符串比较区分大小写,所以您应该监听eloquent.saved: Episode 事件。注意Episode 上的大写E。触发事件时,类名不会转换为小写。

此外,虽然这不适用于您的特定情况,但应注意,如果该类是在命名空间下定义的,例如 App,您还需要包含该命名空间(即 App\Episode )。

【讨论】:

    猜你喜欢
    • 2023-03-07
    • 1970-01-01
    • 2017-12-22
    • 1970-01-01
    • 1970-01-01
    • 2017-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多