Last active
October 8, 2016 11:28
-
-
Save leonardfactory/d21f3787594306374ce336d9c5e9cdbb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Fields.yaml del tuo 'Pet' | |
# Utilizziamo 'petSaveData' solo per passare i dati all'evento 'beforeSave' | |
pet_save_data[species]: | |
label: Specie | |
type: text | |
# ... | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class PetsPlugin { | |
public boot() { | |
User::extend(function($model) { | |
// Evitiamo di salvare i 'pet_save_data' nel DB | |
$model->purgeable[] = ['pet_save_data']; | |
// Quando viene salvato un User, provvediamo a salvare anche il Pet correlato | |
$model->bindEvent('beforeSave', function($user) { | |
$pet = Pet::where('user_id', $user->id)->findOne(); | |
if (empty($pet)) { | |
$pet = new Pet(); | |
$pet->user_id = $user->id; | |
} | |
$pet->species = $user->pet_save_data['species']; | |
/* ... */ | |
$pet->save(); | |
}); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment