• Reading time ~ 1 min
  • 20.01.2025

When working with Eloquent models, sometimes you need just the core database attributes without relationships or computed properties. Laravel's attributesToArray method provides a clean way to access this raw model data.

// Basic usage
$user = User::first();
$attributes = $user->attributesToArray();
// Returns raw database attributes
// ['id' => 1, 'name' => 'John', 'email' => '[email protected]']

Let's explore a practical example implementing an audit system for model changes:

<?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);
    }
}

The attributesToArray method provides direct access to model attributes as stored in the database, making it perfect for scenarios where you need the raw data without additional computed properties or relationships.

Comments

No comments yet
Yurij Finiv

Yurij Finiv

Full stack

ABOUT

Professional Fullstack Developer with extensive experience in website and desktop application development. Proficient in a wide range of tools and technologies, including Bootstrap, Tailwind, HTML5, CSS3, PUG, JavaScript, Alpine.js, jQuery, PHP, MODX, and Node.js. Skilled in website development using Symfony, MODX, and Laravel. Experience: Contributed to the development and translation of MODX3 i...

About author CrazyBoy49z
WORK EXPERIENCE
Contact
Ukraine, Lutsk
+380979856297

We shoot down "Shahed" drones every day. Each one downed means lives saved. But we need mobility: a van or a trailer. Every donation = another night under protection.

🚐 Van fundraiser for my unit, 1020 regiment 🎯 Goal: 500,000 ₴
🔗 Donation link 💳 4441 1111 2546 4663