laravel model callbacks after save, before save, etc

后端 未结 7 2094
傲寒
傲寒 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:09

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

    NOTE: saving or 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.

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

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

提交回复
热议问题