You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

98 lines
2.1 KiB

2 years ago
  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Database\Eloquent\Factories\HasFactory;
  4. use Illuminate\Database\Eloquent\Model;
  5. use Illuminate\Support\Facades\DB;
  6. class User extends Model
  7. {
  8. use HasFactory;
  9. public $dirties = [];
  10. public $originalModel = [];
  11. protected $fillable = ['name', 'email', 'status'];
  12. protected $casts = [
  13. 'status' => 'boolean',
  14. 'created_at' => 'datetime',
  15. 'updated_at' => 'datetime'
  16. ];
  17. public function getNameAttribute($value)
  18. {
  19. return $value . '______';
  20. }
  21. protected static function boot()
  22. {
  23. parent::boot();
  24. // static::saved(function(Model $model) {
  25. // dd(
  26. // 'here inside saving'
  27. // ) ;
  28. // });
  29. }
  30. public function saveRich()
  31. {
  32. try {
  33. DB::beginTransaction();
  34. $this->dirties = $this->getDirty();
  35. $this->originalModel = $this->getOriginal();
  36. $this->save();
  37. $this->sendEvents();
  38. DB::commit();
  39. } catch (\Exception $e) {
  40. DB::rollBack();
  41. dd($e);
  42. }
  43. }
  44. protected function modelUpdated(): bool {
  45. return !$this->wasRecentlyCreated && isset($this->getChanges()['updated_at']);
  46. }
  47. public function hasDirty(): bool {
  48. return array_count_values($this->dirties) > 0;
  49. }
  50. public function getOldDirty(): array {
  51. $old = [];
  52. foreach (array_keys($this->dirties) as $dirtyField) {
  53. $old[$dirtyField] = $this->originalModel[$dirtyField];
  54. }
  55. return $old;
  56. }
  57. protected function dispatchModelEvents(): array
  58. {
  59. $events = [];
  60. if ($this->wasRecentlyCreated) {
  61. $events[] = 'created_at event is set';
  62. }
  63. if (isset($this->dirties['name'])) {
  64. $events[] = 'name event is added';
  65. }
  66. if ($this->modelUpdated()) {
  67. $events[] = 'updated_at event is added';
  68. }
  69. return $events;
  70. }
  71. protected function sendEvents()
  72. {
  73. $events = $this->dispatchModelEvents();
  74. print_r($events);
  75. }
  76. }