Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

GeorgeKala's avatar

Laravel Query optimization, and efficient Way to Calculate Employee KPIs

Hi everyone,

I'm working on a system to calculate employee KPIs based on the actions they take during negotiations, this functionality contains returning of KPI and percentage of employee's kpi, according its created action, i am creating KPI here choose action option and quantity of each action option and add, after i should calculate of each kpi item according employees created actions which has also action option. I have the following models

Employee:

Action:

ActionOption

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class ActionOption extends Model
{
    protected $fillable = ['name', 'buyer_organization_id'];

    public function buyerOrganization(): BelongsTo
    {
        return $this->belongsTo(BuyerOrganization::class);
    }

    public function actions(): HasMany
    {
        return $this->hasMany(Action::class);
    }
}

Kpi:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Kpi extends Model
{
    protected $fillable = ['employee_id', , 'kpi_date', ];

    public function employee(): BelongsTo
    {
        return $this->belongsTo(Employee::class);
    }

   

    public function kpiItems(): HasMany
    {
        return $this->hasMany(KPIItem::class);
    }
}

and KpiItem

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class KpiItem extends Model
{
    protected $fillable = ['kpi_id', 'action_option_id', 'assigned_quantity'];

    public function kpi(): BelongsTo
    {
        return $this->belongsTo(KPI::class);
    }

    public function actionOption(): BelongsTo
    {
        return $this->belongsTo(ActionOption::class);
    }
}

this is logic of creation, and getting of calculated kpi data according its items and created actions:

  • what is the best way to do functionality and calculations like this, Are there any potential optimizations I might be overlooking.
  • Is there a more efficient way to achieve the same result using Laravel's query builder or other techniques? -Has anyone else implemented a similar KPI calculation for actions in their Laravel applications? Sharing experiences and alternative approaches would be greatly appreciated.
0 likes
1 reply

Please or to participate in this conversation.