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

rojonunoo's avatar

Performing Multiple Calculations before storing into Database

I have a student Model . Real life ( a student has a fixed amount i.e school fees ) how do i keep calculating the students fees everytime a student makes a payment . Like Student A has fees of $400. First week of school he pays $200 and now he has a balance of $200. and following month he made a payment of another $200 and now his balance is 0, meaning he is not owing anymore . this is how i thought i could do but it really work .

public function store(Request $request,$id) { $student = Student::FindorFail($id);

    if(count($student->fees)  )
        echo 'true';
    else
        echo 'false' . '<br>';

    $school_fees = $student->student_fees;
    
    $fees = new Fees();
    $fees->student_id= $student->id;
    $fees->payment_method = $request['payment_method'];
    $fees->bank_name = $request['bank_name'];
    $fees->account_no = $request['account_no'];
    $fees->amount = $request['amount'];
    $fees->balance = $school_fees - $fees->amount;
    $fees->save();
    
     echo $fees .  '<br>' . 'Student Original Fees is ' . $school_fees . '<br> Amount Paid : ' . $fees->amount . '<br> Balance : ' .$fees->balance;

}

public function up() { Schema::create('students', function (Blueprint $table) {

        $table->engine = 'InnoDB';

        $table->increments('id');
        $table->string('name');
        $table->date('dob');
        $table->string('last_school_attended');
        $table->string('avatar')->default();
        $table->decimal('student_fees');
        $table->softDeletes('deleted_at');
        $table->timestamps();
    });
}

{ Schema::create('fees', function (Blueprint $table) {

        $table->increments('id');
        $table->unsignedInteger('student_id')->unsigned();
        $table->string('payment_method');
        $table->string('bank_name')->nullable();
        $table->string('account_no')->nullabe();
        $table->decimal('balance');
        $table->decimal('amount');
        $table->date('date');
        $table->timestamps();

        $table->foreign('student_id')
            ->references('id')->on('students')
            ->onDelete('cascade')
            ->onUpdate('cascade');
    });
0 likes
0 replies

Please or to participate in this conversation.