Points allocation based on Time - Laravel 5.3

Updated: Feb 21, 2025

Points allocation based on Time - Laravel 5.3

In Laravel 5.3, if you want to allocate points based on time, you can create a simple system using the Eloquent ORM and the Carbon library for handling dates and times. Here's a step-by-step guide to creating a points system that allocates points based on the elapsed time.

  1. Create a User model:

First, create a User model if you haven't already. You can use the following command to create the model:

php artisan make:model User

Next, open the app/User.php file and add the following code to the fillable property:

protected $fillable = ['name', 'email', 'points'];
  1. Create a Points model:

Create a new model called Points using the following command:

php artisan make:model Points

Open the app/Points.php file and add the following code to the fillable property:

protected $fillable = ['user_id', 'points'];
  1. Define the relationship between User and Points:

Open the app/User.php file and add the following code to define the relationship between User and Points:

public function points()
{
    return $this->hasMany(Points::class);
}

Open the app/Points.php file and add the following code to define the inverse relationship:

public function user()
{
    return $this->belongsTo(User::class);
}
  1. Create a method to calculate and allocate points:

Open the app/User.php file and add the following method to calculate and allocate points based on elapsed time:

public function addPointsForTime($minutes)
{
    $points = $minutes * 5; // You can set the points per minute as a constant or a config value

    $this->points += $points;
    $this->save();

    $this->points()->create([
        'points' => $points,
    ]);
}
  1. Test the points allocation:

You can test the points allocation by using the following code in your controller or anywhere in your application:

$user = User::find(1);
$user->addPointsForTime(60); // Allocate 300 points for 1 hour

This is a simple implementation of a points system that allocates points based on elapsed time in Laravel 5.3. You can expand this system by adding more functionality, such as setting different points per minute for different user roles or tracking the start and end times of point-earning activities.