Exemple #1
0
 public static function boot()
 {
     parent::boot();
     // Attach event handler, on deleting of the user
     User::deleting(function ($user) {
         // for each post that the user has modified set the modified by user to null
         foreach ($user->modifiedPosts as $modifiedPost) {
             $modifiedPost->update_user_id = null;
             $modifiedPost->update();
         }
         /*
                     to keep a cascading delete when using softDeletes we must remove the related models here
         */
         $children = ['comments', 'sections', 'views', 'messages', 'sentMessages', 'activity', 'givenComments'];
         Log::info("Deleting User {$user->username} - {$user->id}");
         foreach ($children as $child) {
             if ($user->{$child}()) {
                 // we need to call delete on the grandchilden to
                 // trigger their delete() events - seems dumb
                 if (get_class($user->{$child}) === 'Illuminate\\Database\\Eloquent\\Collection') {
                     foreach ($user->{$child} as $grandchild) {
                         Log::info(" - removing grandchildren of user->{$child}");
                         $grandchild->delete();
                     }
                 } else {
                     Log::info(" - removing user->{$child}");
                     $user->{$child}->delete();
                 }
             }
         }
     });
 }