laravel model callbacks after save, before save, etc

后端 未结 7 2087
傲寒
傲寒 2020-11-30 09:34

Are there callbacks in Laravel like:

afterSave()
beforeSave()
etc

I searched but found nothing. If there are no such things - what is best

7条回答
  •  抹茶落季
    2020-11-30 10:06

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

    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 = new Page;
    $page->title = 'My Title';
    $page->save();
    

提交回复
热议问题