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

DogRocker's avatar

Get lastest record from many to many table

Hello, I confuse about many to many eloquent about how to get the lastest select item from many to many table.

I have 3 tables like items, warehouses, warehouse_history.

items
id | name
1  | item1 
2  | item2
3 | item3
warehouses
id | name
1  | warehouse1
2  | warehouse2
warehouse_history
id | warehose_id | item_id
1   | 1                |  1
2  | 2               |  2
3  | 2               |  1
4  | 1                |  1
5  | 2               |  1
6  | 1                | 2
7  | 1                | 3

Now I want to get all item in items table with lastest warehouses_id.

this is I want
foreach($items as $item) {
    $item->warehouse;
}
It will be look like this
item_name | warehouse_name
item1           |  warehouse2
item2          |  warehouse1
item3          |  warehouse1

How can I make this with Eloquent or I should use Fluent Query ?

Thanks.

0 likes
5 replies
mstnorris's avatar

Below I have detailed how you should set up your relationships. Make sure that you have $table->timestamps() on your pivot table.

I'm not sure exactly what you're asking, please can you confirm what data you want to get, what constraints you want to use and I'll try and help.

Item Model

public function warehouses() {
    return $this->belongsToMany('App\Warehouse', 'warehouse_history', 'item_id', 'warehouse_id')->withTimestamps();
}

Warehouse Model

public function items() {
    return $this->belongsToMany('App\Item', 'warehouse_history', 'warehouse_id', 'item_id')->withTimestamps();
}
DogRocker's avatar

Thanks @mstnorris . I already add the relation but I don't know how to make the query.

I updated my question.

JarekTkaczyk's avatar

@DogRocker If you really want just items related to latest warehouse, then it's simple:

$latestWarehouse = Warehouse::latest()->first(); // or latest('id') if that's the column you're interested in
$items = $latestWarehouse->items;
DogRocker's avatar

@JarekTkaczyk I follow your solution

it return

item_name | warehouse_name
item1           |  warehouse2
item2          |  warehouse1

but I want

item_name | warehouse_name
item1           |  warehouse2
item2          |  warehouse1
item3          |  warehouse1
DogRocker's avatar

I trying this solution.

$items = item::all();
        foreach($items as $item) {
            dump($item->warehouses);
        }
        dd();

It return

item1
    warehouse1
    warehouse2
    warehouse1
    warehouse2
item2
     warehouse2
     warehouse1
item3
     warehouse1

But I want only

item1
    warehouse2
item2
     warehouse1
item3
     warehouse1

Don't know how to get that.

Please or to participate in this conversation.