Advanced Eloquent Usage

Accessors & Mutators

Accessors and mutators allow you to format and transform model attributes when getting or setting them.

Example:

use Illuminate\Database\Eloquent\Casts\Attribute;

class User extends Model {
    // Accessor & Mutator for full name
    protected function fullName(): Attribute
    {
        return Attribute::make(
            get: fn ($value, $attributes) => $attributes['first_name'] . ' ' . $attributes['last_name'],
            set: fn ($value) => [
                'first_name' => explode(' ', $value)[0] ?? '',
                'last_name' => explode(' ', $value)[1] ?? '',
            ],
        );
    }
}
  • Use the Attribute class for custom accessors and mutators.
  • Define accessors and mutators as protected methods named after the attribute.

Attribute Casting (Laravel 12.x)

Attribute casting now uses protected methods instead of the $casts property for custom casts. Refer to the official docs: https://laravel.com/docs/12.x/eloquent-mutators#cast-parameters

Example:

use Illuminate\Database\Eloquent\Casts\AsHash;

class User extends Model {
    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'secret' => AsHash::class.':sha256',
        ];
    }
}
  • Use the casts() method to define attribute casts with parameters.

Reference: See the official docs for more: https://laravel.com/docs/12.x/eloquent-mutators#cast-parameters

Soft Deletes

Use the SoftDeletes trait to allow models to be "deleted" without removing them from the database.

use Illuminate\Database\Eloquent\SoftDeletes;
class User extends Model {
    use SoftDeletes;
}
  • Soft deleted records are excluded from queries by default.
  • Use withTrashed() and onlyTrashed() to query soft deleted records.

Timestamps

Laravel automatically manages created_at and updated_at fields. You can disable this by setting $timestamps = false.

class LogEntry extends Model {
    public $timestamps = false;
}
  • Use timestamps for auditing and tracking changes.

Best Practices

  • Prefer the new Attribute class syntax for custom accessors and mutators.
  • Use soft deletes for recoverable data.
  • Document custom accessors, mutators, and casts in model PHPDoc.
  • Reference the official Laravel docs for advanced usage and updates.

Example: Comprehensive Model

class Product extends Model {
    use SoftDeletes;

    // Accessor for formatted price
    protected function formattedPrice(): Attribute
    {
        return Attribute::make(
            get: fn ($value, $attributes) => '$' . number_format($attributes['price'], 2),
        );
    }
    // Mutator for tags
    protected function tags(): Attribute
    {
        return Attribute::make(
            set: fn ($value) => json_encode($value),
        );
    }
}