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

StarShines's avatar

Showing Amount from Related Table

Hello,

I have three tables:

  1. Feeplan
  2. Student
  3. Invoice

Feeplan is linked with Student like below:

public function studentName()
    {
        return $this->belongsTo(Student::class);
    }

Feeplan is linked with Invoice like below:


public function studentInvoices()
    {
        return $this->belongsToMany(Invoice::class);
    }

Invoice is linked with Student like below:


public function studentName()
    {
        return $this->belongsToMany(Student::class);
    }

Invoice is linked with Feeplan like below:


public function studentFee()
    {
        return $this->belongsToMany(Feeplan::class);
    }

On Invoice Create Page, I use Select2 to select multiple students and show it on Invoice Show Page like this:


<td>
                            @foreach($invoice->studentName as $key => $entry)
                                <li><span>{{ $entry->student_name }}</span></li>
                            @endforeach
</td>

However, for amount, when I do the below, it ONLY gives one student's invoice amount (NOT for all selected student):


<td>
                            @foreach($invoice->studentFee as $key => $entry)
                            <li><span>{{ $entry->student_fee }}</span></li>
                            @endforeach
</td>

So if I can choose mutiple students in Select2, how can I show their fee in the amount column using above relations?

Many thanks

0 likes
4 replies
LaryAI's avatar
Level 58

To show the fee for all selected students in the amount column, you can loop through the selected students and their corresponding fees using nested foreach loops. Here's an example:

<td>
    @foreach($invoice->studentName as $student)
        @foreach($student->studentFee as $fee)
            <li><span>{{ $fee->student_fee }}</span></li>
        @endforeach
    @endforeach
</td>

This will loop through all selected students and their corresponding fees and display them in the amount column.

StarShines's avatar

@LaryAI Hi Lary,

I am getting the following error:

foreach() argument must be of type array|object, null given....on this line:

@foreach($student->studentFee as $fee)
StarShines's avatar

@newbie360 Thanks for your reply.

In invoices, students (student_name) are coming from Student Table. The student fee (student_fee) comes from Feeplan table.

Also invoice and feeplan tables are related, many to many.

So the withSum will not work.

Please or to participate in this conversation.