Laravel Tutorials

Accessing Raw Model Data with Laravel's attributesToArray Method

Published Updated
Accessing Raw Model Data with Laravel's attributesToArray Method image

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' => 'john@example.com']

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.

Harris Raftopoulos photo

Senior Software Engineer • Staff & Educator @ Laravel News • Co-organizer @ Laravel Greece Meetup

Sponsored

tinkerwell logo
Tinkerwell

Enjoy coding and debugging in an editor designed for fast feedback and quick iterations. It's like a shell for your application – but with multi-line editing, code completion, and more.

Visit Tinkerwell

The latest

View all →
CPX: The Composer Package Executor for PHP image

CPX: The Composer Package Executor for PHP

Read article
Laravel AI SDK Adds Human-in-the-Loop Tool Approval image

Laravel AI SDK Adds Human-in-the-Loop Tool Approval

Read article
Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals image

Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals

Read article
Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs image

Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs

Read article
Blade Formatting in Laravel Pint image

Blade Formatting in Laravel Pint

Read article
Inertia DevTools Is Now on the Chrome Web Store image

Inertia DevTools Is Now on the Chrome Web Store

Read article