При роботі з моделями Eloquent іноді потрібні тільки основні атрибути бази даних без зв'язків або обчислюваних властивостей. Метод Laravel attributesToArray забезпечує чистий спосіб доступу до цих необроблених даних моделі.
// Basic usage
$user = User::first();
$attributes = $user->attributesToArray();
// Returns raw database attributes
// ['id' => 1, 'name' => 'John', 'email' => '[email protected]']
Давайте розглянемо практичний приклад реалізації системи аудиту для змін моделі:
<?php
namespace App\Models;
use App\Models\AuditLog;
use Illuminate\Database\Eloquent\Model;
class AuditableModel extends Model
{
protected static function booted()
{
static::updated(function ($model) {
$original = $model->getOriginal();
$current = $model->attributesToArray();
// Compare only actual database attributes
$changes = array_diff($current, $original);
if (!empty($changes)) {
AuditLog::create([
'model_type' => get_class($model),
'model_id' => $model->id,
'original' => json_encode($original),
'changes' => json_encode($changes),
'user_id' => auth()->id(),
'timestamp' => now()
]);
}
});
}
}
class Product extends AuditableModel
{
protected $appends = ['formatted_price', 'stock_status'];
public function category()
{
return $this->belongsTo(Category::class);
}
public function getFormattedPriceAttribute()
{
return "$" . number_format($this->price / 100, 2);
}
}
метод attributesToArray забезпечує прямий доступ до атрибутів моделі, які зберігаються в базі даних, що робить його ідеальним для сценаріїв, де вам потрібні необроблені дані без додаткових обчислюваних властивостей або зв'язків.