PHPackages                             korridor/laravel-computed-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. [Database &amp; ORM](/categories/database)
4. /
5. korridor/laravel-computed-attributes

ActiveLibrary[Database &amp; ORM](/categories/database)

korridor/laravel-computed-attributes
====================================

Laravel package that adds computed attributes to eloquent models. A computed attribute is an accessor were the computed value is saved in the database.

3.2.0(1y ago)1237.6k↓16.7%4[3 PRs](https://github.com/korridor/laravel-computed-attributes/pulls)MITPHPPHP &gt;=8.1CI passing

Since Dec 6Pushed 5mo ago1 watchersCompare

[ Source](https://github.com/korridor/laravel-computed-attributes)[ Packagist](https://packagist.org/packages/korridor/laravel-computed-attributes)[ Docs](https://github.com/korridor/laravel-computed-attributes)[ RSS](/packages/korridor-laravel-computed-attributes/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (9)Versions (14)Used By (0)

Laravel computed attributes
===========================

[](#laravel-computed-attributes)

[![Latest Version on Packagist](https://camo.githubusercontent.com/bf9ea8ba6040b2ec93d9783f9fda47c6cdab0b4c3763f885b1a3c6fe9c6cccdf/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6b6f727269646f722f6c61726176656c2d636f6d70757465642d617474726962757465733f7374796c653d666c61742d737175617265)](https://packagist.org/packages/korridor/laravel-computed-attributes)[![License](https://camo.githubusercontent.com/faf86b6e1b93eeaa99b4f58b03ea431897c427adc7c49299eeeb6ebe2e45ecb4/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6b6f727269646f722f6c61726176656c2d636f6d70757465642d617474726962757465733f7374796c653d666c61742d737175617265)](license.md)[![Supported PHP versions](https://camo.githubusercontent.com/ddf82e5024ae30232e1ad37245ea811c47f7a1bb35258ae6e5530f873054d672/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f6b6f727269646f722f6c61726176656c2d636f6d70757465642d617474726962757465733f7374796c653d666c61742d737175617265)](https://packagist.org/packages/korridor/laravel-computed-attributes)[![GitHub Workflow Lint](https://camo.githubusercontent.com/02f5416a20104399923d2c30c5909faca58920198cf1a3ab07c5e36cb3037d51/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6b6f727269646f722f6c61726176656c2d636f6d70757465642d617474726962757465732f6c696e742e796d6c3f6c6162656c3d6c696e74267374796c653d666c61742d737175617265)](https://github.com/korridor/laravel-computed-attributes/actions/workflows/lint.yml)[![GitHub Workflow Tests](https://camo.githubusercontent.com/55da55cd6bad33ea7ef9d387cd2ad30e8356b26cc229a174b4204d21c86a198a/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6b6f727269646f722f6c61726176656c2d636f6d70757465642d617474726962757465732f756e697474657374732e796d6c3f6c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/korridor/laravel-computed-attributes/actions/workflows/unittests.yml)[![Codecov](https://camo.githubusercontent.com/4c95ad76c453c7df3303958fa48cfb5ffb4f7302e13357c169abd6ae1e5abe10/68747470733a2f2f696d672e736869656c64732e696f2f636f6465636f762f632f6769746875622f6b6f727269646f722f6c61726176656c2d636f6d70757465642d617474726962757465733f7374796c653d666c61742d737175617265)](https://codecov.io/gh/korridor/laravel-computed-attributes)

Laravel package that adds computed attributes to eloquent models. A computed attribute is an accessor where the value is saved in the database. The value can be regenerated or validated at any time. This can increase performance (no calculation at every get/fetch) and it can simplify querying the database (f.e. complex filter system).

Note

Check out **solidtime - The modern Open Source Time-Tracker** at [solidtime.io](https://www.solidtime.io)

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

[](#installation)

You can install the package via composer with following command:

```
composer require korridor/laravel-computed-attributes
```

If you want to use this package with older Laravel/PHP version please install the 2.2.\* version.

```
composer require korridor/laravel-computed-attributes "^2.2"
```

You can also publish the config file to change the default configuration (e.g. the model folder path).

```
php artisan vendor:publish --tag=computed-attributes-config
```

### Requirements

[](#requirements)

This package is tested for the following Laravel and PHP versions:

- 12.\* (PHP 8.2, 8.3, 8.4)
- 11.\* (PHP 8.2, 8.3, 8.4)
- 10.\* (PHP 8.1, 8.2, 8.3)

Usage examples
--------------

[](#usage-examples)

Here is an example of two computed attributes `complex_calculation` and `sum_of_votes`. The functions `getComplexCalculationComputed` and `getSumOfVotesComputed` are calculating the computed attributes.

```
use Illuminate\Database\Eloquent\Model;
use Korridor\LaravelComputedAttributes\ComputedAttributes;

class Post extends Model {

    use ComputedAttributes;

    /**
     * The attributes that are computed. (f.e. for performance reasons)
     * These attributes can be regenerated at any time.
     *
     * @var string[]
     */
    protected $computed = [
        'complex_calculation',
        'sum_of_votes',
    ];

    /*
     * Computed attributes.
     */

    /**
     * @return int
     */
    public function getComplexCalculationComputed(): int
    {
        return 1 + 2;
    }

    /**
     * @return int
     */
    public function getSumOfVotesComputed(): int
    {
        return $this->votes->sum('rating');
    }

    // ...
}
```

```
/**
 * Boot function from laravel.
 */
protected static function boot(): void
{
    static::saving(function (Post $model) {
        $model->setComputedAttributeValue('sum_of_votes');
    });
    parent::boot();
}
```

For the whole code of this very simple example see the `tests/TestEnvironment` folder.

Commands
--------

[](#commands)

### computed-attributes:generate

[](#computed-attributesgenerate)

```
computed-attributes:generate { modelsAttributes? } { --chunkSize=500 } { --chunk= }

```

This command (re-)calculates the values of the computed attributes and saves the new value.

#### Query optimization

[](#query-optimization)

You can use the `computedAttributesGenerate` scope in any model using the `ComputedAttributes` trait to extend the query that fetches the models for the calculation.

```
use Illuminate\Database\Eloquent\Builder;

// ...

/**
 * This scope will be applied during the computed property generation with artisan computed-attributes:generate.
 *
 * @param Builder $builder
 * @param array $attributes Attributes that will be generated.
 * @return Builder
 */
public function scopeComputedAttributesGenerate(Builder $builder, array $attributes): Builder
{
    if (in_array('sum_of_votes', $attributes)) {
        return $builder->with('votes');
    }

    return $builder;
}
```

### computed-attributes:validate

[](#computed-attributesvalidate)

```
artisan computed-attributes:validate { modelsAttributes? } { --chunkSize=500 } { --chunk= }

```

This command validates the current values of the computed attributes.

#### Query optimization

[](#query-optimization-1)

```
use Illuminate\Database\Eloquent\Builder;

// ...

/**
 * This scope will be applied during the computed property validation with artisan computed-attributes:validate.
 *
 * @param Builder $builder
 * @param array $attributes Attributes that will be validated.
 * @return Builder
 */
public function scopeComputedAttributesValidate(Builder $builder, array $attributes): Builder
{
    if (in_array('sum_of_votes', $attributes)) {
        return $builder->with('votes');
    }

    return $builder;
}
```

Contributing
------------

[](#contributing)

I am open for suggestions and contributions. Just create an issue or a pull request.

### Local docker environment

[](#local-docker-environment)

The `docker` folder contains a local docker environment for development. The docker workspace has composer and xdebug installed.

```
docker-compose run workspace bash
```

### Testing

[](#testing)

The `composer test` command runs all tests with [phpunit](https://phpunit.de/). The `composer test-coverage` command runs all tests with phpunit and creates a coverage report into the `coverage` folder.

### Codeformatting/Linting

[](#codeformattinglinting)

The `composer fix` command formats the code with [php-cs-fixer](https://github.com/FriendsOfPHP/PHP-CS-Fixer). The `composer lint` command checks the code with [phpcs](https://github.com/squizlabs/PHP_CodeSniffer).

License
-------

[](#license)

This package is licensed under the MIT License (MIT). Please see [license file](license.md) for more information.

###  Health Score

49

—

FairBetter than 95% of packages

Maintenance58

Moderate activity, may be stable

Popularity38

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity73

Established project with proven stability

 Bus Factor1

Top contributor holds 86.4% 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.

###  Release Activity

Cadence

Every ~191 days

Recently: every ~249 days

Total

11

Last Release

441d ago

Major Versions

v0.0.3 → v1.0.02020-09-27

v1.0.1 → v2.0.02021-11-02

2.2.1 → 3.0.02023-02-16

PHP version history (6 changes)v0.0.1PHP ^7.1|^7.2|^7.3

v0.0.3PHP ^7.1|^7.2|^7.3|^7.4

v1.0.0PHP ^7.1

v2.0.0PHP ^7.2|^8.0

v2.1.0PHP ^7.2|^8

3.0.0PHP &gt;=8.1

### Community

Maintainers

![](https://www.gravatar.com/avatar/728181ca75a1f175821f8adf7526047da19253c88ec012b236031f4fab1c5cf0?d=identicon)[korridor](/maintainers/korridor)

---

Top Contributors

[![korridor](https://avatars.githubusercontent.com/u/26689068?v=4)](https://github.com/korridor "korridor (19 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (3 commits)")

---

Tags

accessorcachingdatabaseeloquenteloquent-modelslaravelmodelpackageperformancelaravelperformancemodeleloquentcachingaccessorattributecomputed

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

### Embed Badge

![Health badge](/badges/korridor-laravel-computed-attributes/health.svg)

```
[![Health](https://phpackages.com/badges/korridor-laravel-computed-attributes/health.svg)](https://phpackages.com/packages/korridor-laravel-computed-attributes)
```

###  Alternatives

[tucker-eric/eloquentfilter

An Eloquent way to filter Eloquent Models

1.8k4.8M26](/packages/tucker-eric-eloquentfilter)[mongodb/laravel-mongodb

A MongoDB based Eloquent model and Query builder for Laravel

7.1k7.2M71](/packages/mongodb-laravel-mongodb)[spiritix/lada-cache

A Redis based, automated and scalable database caching layer for Laravel

591444.8k2](/packages/spiritix-lada-cache)[ymigval/laravel-model-cache

Laravel package for caching Eloquent model queries

7642.2k3](/packages/ymigval-laravel-model-cache)[astrotomic/laravel-cachable-attributes

Allows to cache attribute accessor values in an easy way.

3240.0k](/packages/astrotomic-laravel-cachable-attributes)[sebastiaanluca/laravel-boolean-dates

Automatically convert Eloquent model boolean attributes to dates (and back).

40111.7k1](/packages/sebastiaanluca-laravel-boolean-dates)

PHPackages © 2026

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