PHPackages                             eherrera/eloquent-custom-attributes - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. eherrera/eloquent-custom-attributes

ActiveLibrary

eherrera/eloquent-custom-attributes
===================================

Custom attribute handling for Laravel's Eloquent ORM

019PHP

Since Jul 28Pushed 7y ago1 watchersCompare

[ Source](https://github.com/eherrera/eloquent-custom-attributes)[ Packagist](https://packagist.org/packages/eherrera/eloquent-custom-attributes)[ RSS](/packages/eherrera-eloquent-custom-attributes/feed)WikiDiscussions master Synced today

READMEChangelogDependenciesVersions (2)Used By (0)

eloquent-custom-attributes [![Laravel compatibility](https://camo.githubusercontent.com/22a4f337e0669cdca294837d2ca44dacbf5004d65f0ee52fec787f69ff751186/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c61726176656c2d342d677265656e2e737667)](http://laravel.com/) [![Laravel compatibility](https://camo.githubusercontent.com/dd58f710d3d14da6be76abb20b755b14fff099d7cca04f25d16292a4a97e1df4/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c61726176656c2d352d677265656e2e737667)](http://laravel.com/)
======================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================

[](#eloquent-custom-attributes---)

This small library allows you to define custom (virtual) attributes on Eloquent models and use them to interact (or not, if you so choose) with real ones.

Installation
------------

[](#installation)

- Simple composer installation is ok: `composer require eherrera/eloquent-custom-attributes:dev-master `(set version requirement to your favourite)

Usage
-----

[](#usage)

- Add `CustomAttributeHelperTrait` to your model and any number of various attribute handler traits to your model
- Define `$customAttributes` property and list there attribute names together with classes, responsible for their handling
- Override Eloquent's `getAttribute` and `setAttribute` methods so that they work with yout custom attributes
- After that work with your attribute just you are used to. See the example below

```
/**
 * @property array $json_meta_data This attribute is actually of 'string'
 *                                 type in database and in model.
 *                                 But we can work with it just like
 *                                 it is array delegating all underlying
 *                                 operations to JsonAttrHandlerTrait
 */
class Invoice extends Eloquent
{
    use CustomAttributeHelperTrait;
    use JsonAttrHandlerTrait;

    protected $customAttributes = [
        'json_meta_data' => JsonAttrHandlerTrait::class,
    ];

    /**
     * We have to override Eloquent's getAttribute() /
     * setAttribute() on the model directly (not in CustomAttributeHelperTrait)
     * because you might wish to do something in those methods yourself
     */
    public function getAttribute($key)
    {
        if ($this->isCustomAttribute($key)) {
            return $this->getCustomAttribute($key);
        }

        return parent::getAttribute($key);
    }

    public function setAttribute($key, $value)
    {
        if ($this->isCustomAttribute($key)) {
            $this->setCustomAttribute($key, $value);

            return;
        }

        parent::setAttribute($key, $value);
    }

/**
 * Just some simple class to show actual work with model ;)
 */
class Main
{
    public function main() {
        $invoice = Invoice::findOrFail(1);
        $invoice->json_meta_data = ['key' => 'value'];
        $invoice->json_meta_data['key_next'] = 'value_next';

        $invoice->save();
    }
}
```

Interesting
-----------

[](#interesting)

- The name of the custom attribute can be the same as the name of the real attribute of the Laravel model. In this case custom attribute will hide real one and then the interaction with it will be available via responsible trait only (well, you can still access raw attribute values in the `$model->attributes[]` though). But of course you can use another name for a custom attribute to interact with a real one if you need them both to be visible
- You can have one custom attribute (`date` attribute for example) to interact to several underlying real attributes of the model (`day`, `month` and `year`, separately if you wish)

Extending
---------

[](#extending)

Should you want to implement your own custom attribute handler, you have just to implement the trait, responsible for value conversion

- Naming convention for such traits is `AttrHandlerTrait`
- Attribute handling traits must implement two methods: `handleGetAttribute` and `handleSetAttribute`. Check `Json\JsonAttrHandlerTrait` for example
- Be careful with method naming in traits. Don't make them too common since they must nicely co-exist with methods of other traits Eloquent model may use
- If your custom attribute represents complex type (not just a string or a number) consider making a wrapper around it. An example of such wrapper can be `ArrayAttributeWrapper`. It encapsulates an array value, provides access to it and updates corresponding model whenever attribute changes. Wrapper is cached so attribute can be accessed several times from any part of the script

###  Health Score

21

—

LowBetter than 19% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity6

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity43

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 82.6% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

### Community

Maintainers

![](https://www.gravatar.com/avatar/c669a389794a0ac8f11c86b902c5dee85e90e844a7995da9cd2a8892228bf22c?d=identicon)[eherrera](/maintainers/eherrera)

---

Top Contributors

[![FractalizeR](https://avatars.githubusercontent.com/u/318489?v=4)](https://github.com/FractalizeR "FractalizeR (19 commits)")[![eherrera](https://avatars.githubusercontent.com/u/1117483?v=4)](https://github.com/eherrera "eherrera (4 commits)")

### Embed Badge

![Health badge](/badges/eherrera-eloquent-custom-attributes/health.svg)

```
[![Health](https://phpackages.com/badges/eherrera-eloquent-custom-attributes/health.svg)](https://phpackages.com/packages/eherrera-eloquent-custom-attributes)
```

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
