Laravel模型,未调用已删除的回调

时间:2018-10-11 08:24:20

标签: php laravel

im试图在使用我的模型删除行时运行一些其他代码。但是,回调statis::deleted根本没有被触发。

控制器:

/**
 * @param Website $website
 * @param Request $request
 * @return \Illuminate\Http\RedirectResponse
 * @throws \Exception
 */
public function delete(Website $website, Request $request)
{

    $id = $request->input('id-value');

    WebsiteRedirects::query()->where(['website_id' => $website['id'], 'id' => $id])->delete();

    Session::flash('message', [ 'is-success' => [ '1 Redirect has been deleted!' ] ]);

    return back();

}

型号:

class WebsiteRedirects extends Model
{
    protected $table = 'website_redirects';

    protected $guarded = [];

    public $timestamps = false;

    protected static function boot()
    {
        parent::boot();

        static::saved(function ($redirect) {
            PlannerStatus::status('redirect', $redirect->website_id, 1);
        });
        static::deleted(function($redirect) {
            dd('deleted');
            PlannerStatus::status('redirect', $redirect->website_id, 1);
        });
    }
    ...

static::saved工作正常,我也使用query插入。

WebsiteRedirects::query()->create(
            [
                'website_id' => $website->id,
                'redirect_from' => $request->input('redirect-from'),
                'redirect_to' => $request->input('redirect-to')
            ]
        );

3 个答案:

答案 0 :(得分:2)

未调用该事件,因为您不是通过Eloquent删除该行。您将直接删除该行,而不会获取结果-因此Eloquent无法运行已删除的事件。

您必须先获取模型,然后才能删除模型以触发事件。

WebsiteRedirects::where(['website_id' => $website['id'], 'id' => $id])->first()->delete();

添加first()来检索WebsiteRedirect,然后再运行delete()

答案 1 :(得分:0)

在您的代码中

WebsiteRedirects::query()->where(['website_id' => $website['id'], 'id' => $id])

delete()方法之前,对象的实例是Illuminate\Database\Eloquent\Builder不是您的模型。夹将触发Eloquent删除(DB),而不是模型的删除。

答案 2 :(得分:0)

通常,您会做类似的事情:

$user = User::find($id);

$user->delete();