雄弁さモデルを使用すると、関係や計算されたプロパティなしでコアデータベース属性のみが必要な場合があります。 LaravelのAttributestoArrayメソッドは、この生のモデルデータにアクセスするためのクリーンな方法を提供します。
<!-- Syntax highlighted by torchlight.dev -->// Basic usage $user = User::first(); $attributes = $user->attributesToArray(); // Returns raw database attributes // ['id' => 1, 'name' => 'John', 'email' => 'john@example.com']
<!-- Syntax highlighted by torchlight.dev --><?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); } }
以上がlaravel&#039; s属性アレイメソッドを使用した生モデルデータへのアクセスの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。