Laravel 中是否有回调,例如:
afterSave()
beforeSave()
etc
我搜索但一无所获。如果没有这样的事情 - 实现它的最佳方法是什么?
谢谢!
最好的实现方法是在保存回调之前和之后扩展save()函数。
这是一个简单的例子
class Page extends Eloquent {
   public function save(array $options = [])
   {
      // before save code 
      parent::save($options);
      // after save code
   }
}
因此,现在当您保存 Page 对象时,它的save()函数会被调用,其中包含该parent::save()函数;
$page = new Page;
$page->title = 'My Title';
$page->save();
为 Laravel 4 添加一个示例:
class Page extends Eloquent {
    public static function boot()
    {
        parent::boot();
        static::creating(function($page)
        {
            // do stuff
        });
        static::updating(function($page)
        {
            // do stuff
        });
    }
}
实际上,Laravel 在保存|更新|创建一些模型之前|之后有真正的回调。检查这个:
https://github.com/laravel/laravel/blob/3.0/laravel/database/eloquent/model.php#L362
像保存和保存这样的 EventListener 是真正的回调
$this->fire_event('saving'); 
$this->fire_event('saved');
我们该如何处理呢?只需将其分配给此 eventListener 示例:
 \Laravel\Event::listen('eloquent.saving: User', function($user){
  $user->saving();//your event or model function
});
即使这个问题已经被标记为“已接受”——我正在为 Laravel 4 添加一个新的更新答案。
Laravel 4 的 Beta 4 刚刚为 Eloquent 保存事件引入了钩子事件- 所以你不需要再扩展核心:
添加了 Model::creating(Closure) 和 Model::updating(Closure) 方法,用于挂钩 Eloquent 保存事件。感谢 Phil Sturgeon 最终迫使我这样做...... :)
在 Laravel 5.7 中,您可以像这样从命令行创建模型观察者:
php artisan make:observer ClientObserver --model=Client
然后在您的 app\AppServiceProvider 中告诉引导方法要观察的模型和观察者的类名。
use App\Client;
use App\Observers\ClientObserver;
class AppServiceProvider extends ServiceProvider
{
    public function boot()
   {
        Client::observe(ClientObserver::class);
   }
   ...
}
然后在您的 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
    }
    ...
}
我真的很喜欢这种方式的简单性。参考https://laravel.com/docs/5.7/eloquent#events
使用 afarazit 解决方案可能会破坏您的应用程序* 这是固定的工作版本:
注意: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
   }
}
因此,现在当您保存 Page 对象时,它的save()函数会被调用,其中包含该parent::save()函数;
$page = new Page;
$page->title = 'My Title';
if($page->save()){
  echo 'Page saved';
}
afarazit* 我试图编辑他的答案,但没有奏效
如果您想控制模型本身,您可以覆盖保存功能并将您的代码放在之前或之后__parent::save()。
否则,每个 Eloquent 模型都会在保存自己之前触发一个事件。
当 Eloquent 保存模型时,还会触发两个事件。
“eloquent.saving:model_name”或“eloquent.saved:model_name”。