在Laravel中创建,更新或删除任何模型后采取措施 [英] Take an action after any model is created, updated, or deleted in Laravel
问题描述
我想在我的应用程序中每次创建,更新或删除任何模型时都执行一个函数.
I want to execute a function every time ANY model is created, updated, or deleted in my application.
例如,我想将模型名称及其记录数据打印到我的日志中.
For example, I want to print the model name and its record data to my log.
我该怎么做?我一直在寻找可以扩展的课程,但是没有任何运气.
How can I do this? I've been looking for some class to extend, but haven't had any luck.
推荐答案
对Robok答案的评论,您可以使用 BaseObserver
.
Answering to your comment on Robok's answer, you can have a BaseObserver
.
例如,这是我使用的一个:
As example, here is the one I use:
<?php namespace App\Observers;
use Illuminate\Database\Eloquent\Model as Eloquent;
class BaseObserver {
public function saving(Eloquent $model) {}
public function saved(Eloquent $model) {}
public function updating(Eloquent $model) {}
public function updated(Eloquent $model) {}
public function creating(Eloquent $model) {}
public function created(Eloquent $model) {}
public function deleting(Eloquent $model) {}
public function deleted(Eloquent $model) {}
public function restoring(Eloquent $model) {}
public function restored(Eloquent $model) {}
}
现在任何模型观察者都可以扩展它:
Now any model observer can extend it:
<?php namespace App\Observers;
use App\Observers\BaseObserver;
class ProductObserver extends BaseObserver {
public function creating(Eloquent $model)
{
$model->author_id = Sentry::getUser()->id;
}
public function created(Eloquent $model)
{
if(Input::hasFile('logo')) Image::make(Input::file('logo')->getRealPath())->save(public_path() ."/gfx/product/logo_{$model->id}.png");
}
public function updating(Eloquent $model)
{
$model->author_id = Sentry::getUser()->id;
}
public function updated(Eloquent $model)
{
if(Input::has('payment_types')) $model->paymentTypes()->attach(Input::get('payment_types'));
//Upload logo
$this->created($model);
}
}
如果您想在每个观察者中使用类似 $ model-> author_id = Sentry :: getUser()-> id
之类的东西,那么您当然可以在 BaseObserver中应用它
.
If you want to have something like $model->author_id = Sentry::getUser()->id
in every observer, you can of course apply that in the BaseObserver
.
这篇关于在Laravel中创建,更新或删除任何模型后采取措施的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!