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

Gerira's avatar

Fetch data from another table from a hasMany result set?

Hello. I have three tables. ItemOrders, Orders and Items. In my Orders model I have the following:

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use App\Item;

// MODEL
class Order extends Model
{
    public function getItems()
    {
        return $this->hasMany('App\ItemOrder')->select('id');
    }
}

I am calling it inside of my view with

@php $items = $order->getItems @endphp

I am trying to get the names of the items from the hasMany result. How would I achieve something like this? With standard SQL I know how I'd be able to do it, but Eloquent is kinda confusing to me as I'm new at this. Any help or a pointer where/what to look/read would be appreciated.

0 likes
5 replies
Gerira's avatar

Thanks. That works fine but it's not what I'm trying to do. My ItemOrders table has the following structure

id (PK),
item_id (FK),
order_id (FK)

I'm wondering how could I access the item_id foreign key and fetch the name from the Items table?

The logic I'm trying to do is like this (1 to many, many to many...)

Orders:ItemOrders (1:M)

ItemOrders:Items (1:1)
Gerira's avatar

@SaeedPrez

Thanks. I was just playing with tags, I usually use {{ }} in my blade template.

@deselbi Thank you, I believe I figured it out. Took me some time to get acustomed.

LaraStorm's avatar

This works Simple

{{ $order->getItems['name'] }}

Please or to participate in this conversation.