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

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
class User extends Model
{
use HasFactory;
public $dirties = [];
public $originalModel = [];
protected $fillable = ['name', 'email', 'status'];
protected $casts = [
'status' => 'boolean',
'created_at' => 'datetime',
'updated_at' => 'datetime'
];
public function getNameAttribute($value)
{
return $value . '______';
}
protected static function boot()
{
parent::boot();
// static::saved(function(Model $model) {
// dd(
// 'here inside saving'
// ) ;
// });
}
public function saveRich()
{
try {
DB::beginTransaction();
$this->dirties = $this->getDirty();
$this->originalModel = $this->getOriginal();
$this->save();
$this->sendEvents();
DB::commit();
} catch (\Exception $e) {
DB::rollBack();
dd($e);
}
}
protected function modelUpdated(): bool {
return !$this->wasRecentlyCreated && isset($this->getChanges()['updated_at']);
}
public function hasDirty(): bool {
return array_count_values($this->dirties) > 0;
}
public function getOldDirty(): array {
$old = [];
foreach (array_keys($this->dirties) as $dirtyField) {
$old[$dirtyField] = $this->originalModel[$dirtyField];
}
return $old;
}
protected function dispatchModelEvents(): array
{
$events = [];
if ($this->wasRecentlyCreated) {
$events[] = 'created_at event is set';
}
if (isset($this->dirties['name'])) {
$events[] = 'name event is added';
}
if ($this->modelUpdated()) {
$events[] = 'updated_at event is added';
}
return $events;
}
protected function sendEvents()
{
$events = $this->dispatchModelEvents();
print_r($events);
}
}