PHP code example of artificertech / eloquent-attribute-middleware

1. Go to this page and download the library: Download artificertech/eloquent-attribute-middleware library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

artificertech / eloquent-attribute-middleware example snippets

 bash
php artisan make:accessor MyAccessor
 bash
php artisan make:mutator MyMutator
 php
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'
 php
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]);
    }
}