Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: how to create a function After or Before save|update

I need to generate a function to call after or before save() or update() but i don't know how to do. I think I need a callback from save() update() but I don't know how to do. Thanks

like image 239
Daniele Longheu Avatar asked Jul 31 '16 14:07

Daniele Longheu


People also ask

How do you use create or update in Laravel?

Syntax. $flight = Model::updateOrCreate( ['field1' => 'value'], [field=>value, field1=>value] ); The first value in the array is used to search in the table if it exists, and if not it will insert the value or it will update for the match of the first parameters in the array. Let us try an example using it.

What is difference between create and save in Laravel?

What is difference between create and save in Laravel? Save can be used to both create a new Record and update a existing record . Whereas create is used to create a new record by providing all required field at one time .

What does get () do in Laravel?

For creating ::where statements, you will use get() and first() methods. The first() method will return only one record, while the get() method will return an array of records that you can loop over. Also, the find() method can be used with an array of primary keys, which will return a collection of matching records.

What is the difference between insert and create in Laravel?

create() is a function from Eloquent, insert() - Query Builder. In other words, create is just an Eloquent model function that handles the creation of the object to the DB (in a more abstract way). Insert however tries to create the actual query string.


2 Answers

Inside your model, you can add a boot() method which will allow you to manage these events.

For example, having User.php model:

class User extends Model  {      public static function boot()     {         parent::boot();          self::creating(function($model){             // ... code here         });          self::created(function($model){             // ... code here         });          self::updating(function($model){             // ... code here         });          self::updated(function($model){             // ... code here         });          self::deleting(function($model){             // ... code here         });          self::deleted(function($model){             // ... code here         });     }  } 

You can review all available events over here: https://laravel.com/docs/5.2/eloquent#events

like image 67
Mauro Casas Avatar answered Sep 22 '22 18:09

Mauro Casas


This only works after an event happened on your model.

Method 1, using Observers

Create an observer for your model

php artisan make:observer UserObserver --model=User 

this will create an event observer on your model

class UserObserver {     /**      * Handle the User "created" event.      *      * @param  \App\Models\User  $user      * @return void      */     public function created(User $user)     {         //     }      /**      * Handle the User "updated" event.      *      * @param  \App\Models\User  $user      * @return void      */     public function updated(User $user)     {         //     }      /**      * Handle the User "deleted" event.      *      * @param  \App\Models\User  $user      * @return void      */     public function deleted(User $user)     {         //     }      /**      * Handle the User "forceDeleted" event.      *      * @param  \App\Models\User  $user      * @return void      */     public function forceDeleted(User $user)     {         //     } } 

You must register this observer in the boot method on one of your ServiceProviders preferably the AppServiceProvider

// App\Providers\AppServiceProvider.php  public function boot() {     User::observe(UserObserver::class); } 

Method 2, using Closures

You can register custom events in the static booted method of your model

<?php  namespace App;  use Illuminate\Database\Eloquent\Model;  class User extends Model {     /**      * The "booted" method of the model.      *      * @return void      */     protected static function boot()     {         parent::boot();         static::created(function ($user) {             //         });     } } 

Available observable events

// Illuminate\Database\Eloquent\Concerns  /**  * Get the observable event names.  *  * @return array  */ public function getObservableEvents() {     return array_merge(         [             'retrieved', 'creating', 'created', 'updating', 'updated',             'saving', 'saved', 'restoring', 'restored', 'replicating',             'deleting', 'deleted', 'forceDeleted', 'trashed'         ],         $this->observables     ); } 

Note from Laravel documentation

When issuing a mass update via Eloquent, the saving, saved, updating, and updated model events will not be fired for the updated models. This is because the models are never actually retrieved when issuing a mass update.

like image 30
Eboubaker Avatar answered Sep 23 '22 18:09

Eboubaker