PHPackages                             artificertech/eloquent-attribute-middleware - 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. artificertech/eloquent-attribute-middleware

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

artificertech/eloquent-attribute-middleware
===========================================

:package\_description

v1.0(3y ago)0131MITPHPPHP ^8.0.2

Since Dec 13Pushed 3y agoCompare

[ Source](https://github.com/artificertech/eloquent-attribute-middlware)[ Packagist](https://packagist.org/packages/artificertech/eloquent-attribute-middleware)[ Docs](https://github.com/artificertech/eloquent-attribute-middleware)[ RSS](/packages/artificertech-eloquent-attribute-middleware/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (2)Dependencies (4)Versions (4)Used By (0)

EloquentAttributeMiddleware
===========================

[](#eloquentattributemiddleware)

[![Latest Version on Packagist](https://camo.githubusercontent.com/fe57124774b58251e4d764710ffb91bc41cc57b3496d342467003b90db20e7d4/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f617274696669636572746563682f656c6f7175656e742d6174747269627574652d6d6964646c65776172652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/artificertech/eloquent-attribute-middleware)[![Total Downloads](https://camo.githubusercontent.com/9447f11d7835d9b2bf765d6bbbca16e1d9c35da1da520f30c982dc7fc46b1536/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f617274696669636572746563682f656c6f7175656e742d6174747269627574652d6d6964646c65776172652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/artificertech/eloquent-attribute-middleware)[![Build Status](https://camo.githubusercontent.com/7577cd53d2330bd961c25afc2e90af4885ab2162511efef5497a7987fccae1cc/68747470733a2f2f696d672e736869656c64732e696f2f7472617669732f617274696669636572746563682f656c6f7175656e742d6174747269627574652d6d6964646c65776172652f6d61737465722e7376673f7374796c653d666c61742d737175617265)](https://travis-ci.org/artificertech/eloquent-attribute-middleware)[![StyleCI](https://camo.githubusercontent.com/3e5cf7c64120806c3354c6a538f97b82c33d8d843a4cb29e7a6a3d776d784f84/68747470733a2f2f7374796c6563692e696f2f7265706f732f3433373932373138302f736869656c64)](https://styleci.io/repos/437927180)

This package enables you to define middleware classes for your Eloquent model accessors and mutators using php 8 Attributes. This allows you to reuse complex code for your computed attributes. Take a look at [contributing.md](contributing.md) to see a to do list.

Requirements
------------

[](#requirements)

php ^8.0, Laravel ^8

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

[](#installation)

Via Composer

```
composer require artificertech/eloquent-attribute-middleware
```

Usage
-----

[](#usage)

### Accessors

[](#accessors)

create your accessor middleware class using laravel artisan

```
php artisan make:accessor MyAccessor
```

Configure your accessor middleware. Accessor middlware should modify the response of the $next() callback and return the modified value.

```
namespace App\Accessors;

use Artificertech\EloquentAttributeMiddleware\Accessors\Accessor;
use Attribute;
use Closure;

#[Attribute(Attribute::TARGET_METHOD)]
class Upper extends Accessor
{
    /**
     * Run the mutator on the specified model attribute value
     *
     * @param $key the attribute name
     * @param $model the model this attribute is being set for
     * @param $next the next middleware function to call
     * @return mixed
     */
    public function __invoke($key, $model, Closure $next)
    {
        return Str::upper($next());
    }
}
```

Add the middleware functionality to your Eloquent Model

```
...
use App\Accessors\Upper;
use Artificertech\EloquentAttributeMiddleware\Models\Concerns\HasAttributeMiddleware;
...
class User extends Model
{
    use HasAttributeMiddleware;
    ...

    #[Upper]
    public function getNameAttribute($value)
    {
        return $value;
    }
}
```

Now any time you retrieve the name attribute it will be Uppercase

#### Execution Order

[](#execution-order)

Accessors run in order of definition. In the following example the user 'name' attribute is stored in the database as 'Cole Shirley'

```
#[Attribute(Attribute::TARGET_METHOD)]
class Upper extends Accessor
{
    /**
     * make the value uppercase
     *
     * @param $key the attribute name
     * @param $model the model this attribute is being set for
     * @param $next the next middleware function to call
     * @return mixed
     */
    public function __invoke($key, $model, Closure $next)
    {
        return Str::upper($next());
    }
}
...
#[Attribute(Attribute::TARGET_METHOD)]
class AppendTestString extends Accessor
{
    /**
     * append _test to the value
     *
     * @param $key the attribute name
     * @param $model the model this attribute is being set for
     * @param $next the next middleware function to call
     * @return mixed
     */
    public function __invoke($key, $model, Closure $next)
    {
        return $next() . '_test';
    }
}
...
use App\Accessors\Upper;
use App\Accessors\AppendTestString;
use Artificertech\EloquentAttributeMiddleware\Models\Concerns\HasAttributeMiddleware;
...
class User extends Model
{
    use HasAttributeMiddleware;
    ...

    #[Upper]
    #[AppendTestString]
    public function getNameAttribute($value)
    {
        return $value;
    }
}

$user =  User::find(1);

$user->name; // 'COLE SHIRLEY_TEST'
```

Execution order:

1. the Upper \_\_invoke method is called first which retrieves the value of the next callback
2. the AppendTestString \_\_invoke method is then called which retireves the value of the next callback
3. the getNameAttribute method is called with the value 'Cole Shirley' from the stored model attributes
4. that value is passed back to AppendTestString which then concatenates '\_test' onto the value
5. the modified string is passed back to Upper which makes the entire string uppercase
6. the finalized string is passed back to the implemenation

### Mutators

[](#mutators)

create your mutator middleware class using laravel artisan

```
php artisan make:mutator MyMutator
```

Configure your mutator middleware. Mutator middlware should modify $value parameter before passing it to the $next() callback

```
namespace App\Mutators;

use Artificertech\EloquentAttributeMiddleware\Mutators\Mutator;
use Attribute;
use Closure;

#[Attribute(Attribute::TARGET_METHOD)]
class Lower extends Mutator
{
    /**
     * make the value lowercase
     *
     * @param $value the value of the attribute to set
     * @param $key the attribute name
     * @param $model the model this attribute is being set for
     * @param $next the next middleware function to call
     * @return mixed
     */
    public function __invoke($value, $key, $model, Closure $next)
    {
        return $next(Str::lower($value));
    }
}
```

Add the middleware functionality to your Eloquent Model

```
...
use App\Mutators\Lower;
use Artificertech\EloquentAttributeMiddleware\Models\Concerns\HasAttributeMiddleware;
...
class User extends Model
{
    use HasAttributeMiddleware;
    ...

    #[Lower]
    public function setNameAttribute($value)
    {
        $this->attributes['name'] = $value;
    }
}
```

Now when you set the name attribute it will be lowercased

#### Execution Order

[](#execution-order-1)

Mutators run in order of definition

```
class Lower extends Mutator
{
    /**
     * make the value lowercase
     *
     * @param $value the value of the attribute to set
     * @param $key the attribute name
     * @param $model the model this attribute is being set for
     * @param $next the next middleware function to call
     * @return mixed
     */
    public function __invoke($value, $key, $model, Closure $next)
    {
        return $next(Str::lower($value));
    }
}
...
class WithoutExtraWhitespace extends Mutator
{
    /**
     * make the value lowercase
     *
     * @param $value the value of the attribute to set
     * @param $key the attribute name
     * @param $model the model this attribute is being set for
     * @param $next the next middleware function to call
     * @return mixed
     */
    public function __invoke($value, $key, $model, Closure $next)
    {
        return $next(preg_replace('/\s+/', ' ', $value));
    }
}
...
use App\Mutators\Lower;
use App\Mutators\WithoutExtraWhitespace;
use Artificertech\EloquentAttributeMiddleware\Models\Concerns\HasAttributeMiddleware;
...
class User extends Model
{
    use HasAttributeMiddleware;
    ...

    #[Lower]
    #[WithoutExtraWhitespace]
    public function setNameAttribute($value)
    {
        $this->attributes['name'] = $value;
    }
}

$user = new User;

$user->name = 'Cole   Shirley'; // stored as 'cole shirley'
```

Execution order:

1. the Lower \_\_invoke method is called first with the value 'Cole Shirley'
2. the WithoutExtraWhitespace \_\_invoke method is called with the value 'cole shirley'
3. the setNameAttribute is called with the value 'cole shirley'
4. if the setNameAttribute has a return value it is passed back to the implementation

Practical example: Caching model info from api
----------------------------------------------

[](#practical-example-caching-model-info-from-api)

For most situations you should be able to use normal accessor and mutator functionality. However if you find yourself setting up complicated accessors or mutators repeatedly you may consider extracting that functionality into accessor and mutator middleware. A great example is if you want to cache data related to a model from an external api

```
namespace App\Mutators;

use Artificertech\EloquentAttributeMiddleware\Mutators\Mutator;
use Attribute;
use Closure;

#[Attribute(Attribute::TARGET_METHOD)]
class Cached extends Mutator
{
    /**
     * Check the cache for the attribute
     *
     * @param $key the attribute name
     * @param $model the model this attribute is being set for
     * @param $next the next middleware function to call
     * @return mixed
     */
    public function __invoke($key, $model, Closure $next)
    {
        return Cache::rememberForever($model::class . ":{$model->getKey()}:{$key}", function () use ($value, $next) {
            return $next();
        });
    }
}

...
namespace App\Models;

use App\Mutators\Cached;
use Artificertech\EloquentAttributeMiddleware\Models\Concerns\HasAttributeMiddleware;
...
class User extends Model
{
    use HasAttributeMiddleware;
    ...

    #[Cached]
    public function getApiDataAttribute()
    {
        return Http::get('https://example.com/api/users/', ['name' => $this->name]);
    }
}
```

Change log
----------

[](#change-log)

Please see the [changelog](changelog.md) for more information on what has changed recently.

Testing
-------

[](#testing)

```
composer test
```

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

[](#contributing)

Please see [contributing.md](contributing.md) for details and a todolist.

Security
--------

[](#security)

If you discover any security related issues, please email  instead of using the issue tracker.

Credits
-------

[](#credits)

- [Cole Shirley](https://github.com/coleshirley)
- [All Contributors](../../contributors)

License
-------

[](#license)

MIT. Please see the [license file](license.md) for more information.

###  Health Score

26

—

LowBetter than 43% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity10

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity56

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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 ~179 days

Total

2

Last Release

1428d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/26300af7b89f84f6a6b6ef2ffb592a3e5663b3d8ed7d65a6699a86aab65ed411?d=identicon)[cole.shirley](/maintainers/cole.shirley)

---

Top Contributors

[![coleshirley](https://avatars.githubusercontent.com/u/84236864?v=4)](https://github.com/coleshirley "coleshirley (10 commits)")

---

Tags

laravelEloquentAttributeMiddleware

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/artificertech-eloquent-attribute-middleware/health.svg)

```
[![Health](https://phpackages.com/badges/artificertech-eloquent-attribute-middleware/health.svg)](https://phpackages.com/packages/artificertech-eloquent-attribute-middleware)
```

###  Alternatives

[illuminate/database

The Illuminate Database package.

2.8k52.4M9.3k](/packages/illuminate-database)[tucker-eric/eloquentfilter

An Eloquent way to filter Eloquent Models

1.8k4.8M26](/packages/tucker-eric-eloquentfilter)[watson/validating

Eloquent model validating trait.

9723.3M46](/packages/watson-validating)[cybercog/laravel-love

Make Laravel Eloquent models reactable with any type of emotions in a minutes!

1.2k302.7k1](/packages/cybercog-laravel-love)[cviebrock/eloquent-taggable

Easy ability to tag your Eloquent models in Laravel.

567694.8k3](/packages/cviebrock-eloquent-taggable)[clickbar/laravel-magellan

This package provides functionality for working with the postgis extension in Laravel.

423715.4k1](/packages/clickbar-laravel-magellan)

PHPackages © 2026

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