PHP code example of korridor / laravel-computed-attributes

1. Go to this page and download the library: Download korridor/laravel-computed-attributes 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/ */

    

korridor / laravel-computed-attributes example snippets


use Korridor\LaravelComputedAttributes\ComputedAttributes;

class Post {

    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();
}

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;
}

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;
}
bash
php artisan vendor:publish --tag=computed-attributes-config