Many to Many

Many to Many and the Pivot Table

Orders and products meet in a junction table (ER Model to Tables), which Laravel 2,157 calls the pivot. Both sides declare belongsToMany: Order::products() returns $this->belongsToMany( Product::class, 'order_items'), and Product::orders() mirrors it. Only the table name needs passing, because order_id and product_id match the guessed pivot keys.

Both directions of the order-product linkSQL
use App\Models\{Order, Product};
echo Order::find(2)->products->pluck('title')->join(', '), "\n";
echo Product::find(4)->orders->pluck('id')->join(', '), "\n";
echo Order::find(2)->products()->toRawSql(), "\n";
Output
SQL Queries That Scale, Indexing Deep Dive, Stack Sticker Pack
3, 6, 9
select * from `products` inner join `order_items` on `products`.`id` =
    `order_items`.`product_id` where `order_items`.`order_id` = 2

Each product arrives with a pivot attribute, a generic Relations\Pivot holding only the two keys. The pivot needs no id: its composite primary key (order_id, product_id) also stops a product appearing twice on one order.