php 保存后、保存前等的laravel模型回调

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13518674/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 05:37:11  来源:igfitidea点击:

laravel model callbacks after save, before save, etc

phplaravel

提问by Orbitum

Are there callbacks in Laravel like:

Laravel 中是否有回调,例如:

afterSave()
beforeSave()
etc

I searched but found nothing. If there are no such things - what is best way to implement it?

我搜索了但一无所获。如果没有这样的事情 - 实施它的最佳方法是什么?

Thanks!

谢谢!

采纳答案by Charly Palencia

Actually, Laravel has real callback before|after save|update|create some model. check this:

实际上,Laravel 有真正的回调之前|之后保存|更新|创建一些模型。检查这个:

https://github.com/laravel/laravel/blob/3.0/laravel/database/eloquent/model.php#L362

https://github.com/laravel/laravel/blob/3.0/laravel/database/eloquent/model.php#L362

the EventListener like saved and saving are the real callbacks

像保存和保存这样的 EventListener 是真正的回调

$this->fire_event('saving'); 

$this->fire_event('saved');

how can we work with that? just assign it to this eventListener example:

我们怎样才能做到这一点?只需将它分配给这个 eventListener 示例:

 \Laravel\Event::listen('eloquent.saving: User', function($user){
  $user->saving();//your event or model function
});

回答by afarazit

The best way to achieve before and after save callbacks in to extend the save()function.

最好的方法是实现前后保存回调中的扩展save()功能。

Here's a quick example

这是一个快速示例

class Page extends Eloquent {

   public function save(array $options = [])
   {
      // before save code 
      parent::save($options);
      // after save code
   }
}

So now when you save a Page object its save()function get called which includes the parent::save()function;

所以现在当你保存一个 Page 对象时,它的save()函数被调用,其中包含该parent::save()函数;

$page = new Page;
$page->title = 'My Title';
$page->save();

回答by Nicodemuz

Adding in an example for Laravel 4:

添加 Laravel 4 的示例:

class Page extends Eloquent {

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

        static::creating(function($page)
        {
            // do stuff
        });

        static::updating(function($page)
        {
            // do stuff
        });
    }

}

回答by Laurence

Even though this question has already been marked 'accepted' - I'm adding a new updated answer for Laravel 4.

即使这个问题已经被标记为“已接受” - 我正在为 Laravel 4 添加一个新的更新答案。

Beta 4 of Laravel 4 has just introduced hook events for Eloquent save events- so you dont need to extend the core anymore:

Laravel 4 的 Beta 4 刚刚为 Eloquent 保存事件引入了钩子事件- 所以你不再需要扩展核心:

Added Model::creating(Closure) and Model::updating(Closure) methods for hooking into Eloquent save events. Thank Phil Sturgeon for finally pressuring me into doing this... :)

添加了 Model::creating(Closure) 和 Model::updating(Closure) 方法,用于挂钩 Eloquent 保存事件。感谢 Phil Sturgeon 最终迫使我这样做...... :)

回答by saswanb

In Laravel 5.7, you can create a model observer from the command line like this:

在 Laravel 5.7 中,您可以像这样从命令行创建模型观察者:

php artisan make:observer ClientObserver --model=Client

Then in your app\AppServiceProvider tell the boot method the model to observe and the class name of the observer.

然后在你的 app\AppServiceProvider 中告诉 boot 方法要观察的模型和观察者的类名。

use App\Client;
use App\Observers\ClientObserver;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
   {
        Client::observe(ClientObserver::class);
   }
   ...
}

Then in your app\Observers\ you should find the observer you created above, in this case ClientObserver, already filled with the created/updated/deleted event hooks for you to fill in with your logic. My ClientObserver:

然后在您的 app\Observers\ 中,您应该找到您在上面创建的观察者,在本例中为 ClientObserver,已经填充了 created/updated/deleted 事件挂钩供您填充逻辑。我的客户观察者:

namespace App\Observers;

use App\Client;

class ClientObserver
{

    public function created(Client $client)
    {
        // do your after-model-creation logic here
    }
    ...
}

I really like the simplicity of this way of doing it. Reference https://laravel.com/docs/5.7/eloquent#events

我真的很喜欢这种做法的简单性。参考https://laravel.com/docs/5.7/eloquent#events

回答by safrazik

Your app can break using afarazit solution* Here's the fixed working version:

您的应用程序可能会因使用 afarazit 解决方案而崩溃* 这是固定的工作版本:

NOTE: savingor any other event won't work when you use eloquent outside of laravel, unless you require the events package and boot the events. This solution will work always.

注意:saving除非您需要事件包并启动事件,否则当您在 laravel 之外使用 eloquent 时,或任何其他事件都将不起作用。此解决方案将始终有效。

class Page extends Eloquent {

   public function save(array $options = [])
   {
      // before save code 
      $result = parent::save($options); // returns boolean
      // after save code
      return $result; // do not ignore it eloquent calculates this value and returns this, not just to ignore

   }
}

So now when you save a Page object its save()function get called which includes the parent::save()function;

所以现在当你保存一个 Page 对象时,它的save()函数被调用,其中包含该parent::save()函数;

$page = new Page;
$page->title = 'My Title';
if($page->save()){
  echo 'Page saved';
}

afarazit* I tried to edit his answer but didn't work

afarazit* 我试图编辑他的答案,但没有奏效

回答by Deinumite

If you want control over the model itself, you can override the save function and put your code before or after __parent::save().

如果您想控制模型本身,您可以覆盖 save 函数并将您的代码放在__parent::save().

Otherwise, there is an event fired by each Eloquent model before it saves itself.

否则,每个 Eloquent 模型都会在保存之前触发一个事件。

There are also two events fired when Eloquent saves a model.

当 Eloquent 保存模型时,还会触发两个事件。

"eloquent.saving: model_name" or "eloquent.saved: model_name".

“eloquent.saving:model_name”或“eloquent.saved:model_name”。

http://laravel.com/docs/events#listening-to-events

http://laravel.com/docs/events#listening-to-events