gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-10-31 23:39:41 25 4
gpt4 key购买 nike

我无法在我的事件处理程序中找到用于监听 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com