How do I show multiple value/field from a foreign key?

  eloquent, laravel, laravel-8

Okay so I don’t know how to word my question, so excuse me if it doesn’t make sense

My view

@forelse ($transaction as $key=>$value)
                            <td class="text-center">{{$key + 1}}</th>

My controller

$transaction = Transaction::all();
return view('transaction.index', compact('transaction'));

My model

    // Transaction
    protected $table = 'transaction';
    protected $guarded = [];

    public function transaction_item()
        return $this->hasOne(TransactionItem::class, 'transaction_id');
    // TransactionItem
    protected $table = 'transaction_item';
    protected $guarded = [];
    public $timestamps = false;
    public function transaction()
        return $this->belongsTo(Transaction::class, 'transaction_id');
    public function item()
        return $this->belongsTo(MasterItem::class, 'master_item_id');

Transaction has TransactionItem that has multiple item, quantity, and price. How do I show that to my blade view? When I just do {{$value->transaction_item->item->item_name}}, it only show the first item and also the same for quantity and price. I tried changing item relationship in my TransactionItem to belongsToMany but then this error popped up

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'myDatabase.master_item_id' doesn't exist (SQL: select `master_item`.*, `master_item_id`.`transaction_item_id` as `pivot_transaction_item_id`, `master_item_id`.`master_item_id` as `pivot_master_item_id` from `master_item` inner join `master_item_id` on `master_item`.`id` = `master_item_id`.`master_item_id` where `master_item_id`.`transaction_item_id` = 3)

I’m not sure what causes that problem but, I dont have table or column named transaction_item_id that’s for sure, my table transaction_item primary key is id

Source: Laravel

Leave a Reply