filia_fixi
filia_fixi

Reputation: 19

how to combine 2 columns from different tables into 1 column in 1 table in laravel

I want to combine the number column and the unit column (the unit column is in the unit table). Here's my code:

@foreach ($item as $row)
<tr>
    <td>{{ $row->amount }}</td>
    <td>{{ $row->unit->unit }}</td>
</tr>
@endforeach

and this is the controller

$reports = loan_reports::with('unit')
            ->get();

Please, what should i do?

Upvotes: 0

Views: 303

Answers (1)

Hafez Divandari
Hafez Divandari

Reputation: 9069

There are several solutions for this includes "using join", "using collections", "using API resources" and "define an accessor".

To define a custom accessor, add getUnitAttribute to your loan_reports model:

class loan_reportsextends Model
{
    /**
     * Get the report's unit.
     *
     * @return string
     */
    public function getUnitAttribute()
    {
        return $this->relationLoaded('unit') ? $this->unit->unit : null;
    }
}

Then you can use it like this:

@foreach ($item as $row)
<tr>
    <td>{{ $row->amount }}</td>
    <td>{{ $row->unit }}</td>
</tr>
@endforeach

I have explained other solutions on this answer: https://stackoverflow.com/a/37489962/3477084

Upvotes: 1

Related Questions