Level 88
Well the easiest way is probably in your model. So everytime you save the data in the model you calculate the percentage right.
class Profile extends Model
{
private const PROFILE_FIELDS = ['name', 'email', 'age'];
protected static function boot()
{
parent::boot();
static::saving(function ($model) {
$filledCount = 0;
foreach (self::PROFILE_FIELDS as $field) {
if ($model->{$field} !== null) {
$filledCount++;
}
}
$model->percentage = $filledCount / count(self::PROFILE_FIELDS * 100;
});
}
}
It\s not the most beautiful code, but it should put you in the right direction! You can also use a model observer class instead. Check this part of the documentation: https://laravel.com/docs/5.8/eloquent#events
1 like