Larasou's avatar

Know the percentage of fields filled with a table

Hello everyone,

I would like to create an attribute that will allow me to know the percentage of fields filled with a Model.

As seen with Laracasts with the users profile.

How can I do this simply please?

0 likes
0 replies
bobbybouwmann's avatar

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

Please or to participate in this conversation.