Search code examples
phplaravellaravel-5cronlaravel-5.3

Best practice for updating user 'rank' using a cron job


In my site I have users who can create posts, make a description, upload profile picture, provide email address etc

I want to give users a 'score' or 'rank' depending upon how much they have updated their account. For example, providing a profile pic will be +10 points, a long description will be +5 points, making a post will be +2 points etc

I was going to have a user model method that when executed updates their score and adds it to a column in the users table.

It was suggested to me that I use a cron job for this, and update it once a day as opposed to updating every time the user makes a change to their account.

I was wondering what was best practice for this, and where I should store the user's 'score'.


Solution

  • It would definitely used the Model Events, which are already predefined by Laravel.

    https://laravel.com/docs/5.4/eloquent#events

    So something similar to this, where every time a user is saved, we update the score.

    User::saved(function($user){
        $user->calculateScore();
        $user->save();
    });
    

    This code need to be put in AppServiceProviders boot method.

    In your case this would be best practice, thou in my honest opinion, with no worries you could calculate the score, every time you show it online, that complex can't the calculation be.