Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel model callbacks after save, before save, etc

Tags:

php

laravel

Are there callbacks in Laravel like:

afterSave() beforeSave() etc 

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

Thanks!

like image 283
Orbitum Avatar asked Nov 22 '12 19:11

Orbitum


2 Answers

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(); 
like image 161
afarazit Avatar answered Sep 28 '22 04:09

afarazit


Adding in an example for Laravel 4:

class Page extends Eloquent {      public static function boot()     {         parent::boot();          static::creating(function($page)         {             // do stuff         });          static::updating(function($page)         {             // do stuff         });     }  } 
like image 41
Nicodemuz Avatar answered Sep 28 '22 02:09

Nicodemuz