File: /var/www/ipsremont-demo/app/Observers/PartObserver.php
<?php
namespace App\Observers;
use App\Models\Part;
use Illuminate\Database\Eloquent\Model;
class PartObserver extends BaseObserver
{
private function logPriceChange(Part $part, bool $isCreate = true): void
{
$path = storage_path('logs');
$fileName = date('Y-m-d') . '_part_prices.csv';
$fullPath = $path . '/' . $fileName;
if (file_exists($fullPath)) {
$file = fopen($fullPath, 'ab');
} else {
$file = fopen($fullPath, 'wb');
fwrite($file, "\xEF\xBB\xBF"); // BOM для UTF-8
$columns = [
'Дата',
'Артикул',
'Старая цена',
'Новая цена',
'Действие',
];
fputcsv($file, $columns);
}
$data = [
'Дата' => date('Y-m-d H:i:s'),
'Артикул' => $part->external_id,
'Старая цена' => $isCreate ? null : $part->getOriginal('price'),
'Новая цена' => $part->price,
'Действие' => $isCreate ? 'CREATE' : 'UPDATE',
];
fputcsv($file, $data);
fclose($file);
}
public function created(Model $model)
{
$this->logPriceChange($model);
}
public function updated(Model $model)
{
/** @var Part $model */
$priceChanged = $model->price !== $model->getOriginal('price');
if ($priceChanged) {
$this->logPriceChange($model, false);
}
}
}