Home > Backend Development > PHP Tutorial > Accessing Raw Model Data with Laravel's attributesToArray Method

Accessing Raw Model Data with Laravel's attributesToArray Method

James Robert Taylor
Release: 2025-03-07 01:07:12
Original
791 people have browsed it

Accessing Raw Model Data with Laravel's attributesToArray Method

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.

<!-- 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']
Copy after login

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

<!-- 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);
    }
}
Copy after login

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.

The above is the detailed content of Accessing Raw Model Data with Laravel's attributesToArray Method. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template