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

b_f's avatar
Level 1

Show data of Table and Pivot Table ( belongsToMany )

I have a table with Suppliers that have products, one Supplier can have many products.

I have 3 tables / models:

  • Supplier //data table.
  • Products //data table.
  • ProductSupplierRelation //pivot table.

In the Supplier Model I have this method :

    public function products () {
        return $this->belongsToMany(
            Product::class , 
            ProductSupplierRelation::class , 
            'r_supplier_id' , 
            'r_product_id'
        )
}

In the controller supplier, method show, I want to show one supplier with thier products, is this the correct way ?

class SupplierController extends Controller
{
    public function show ( Supplier $supplier ) {
        return view( 'supplier.show' , [ 
            'supplier' => $supplier , 
            'supplier_products' => $supplier->products
        ] );
    }
}
0 likes
11 replies
tykus's avatar

Why do you have a many-to-many relationship - can a Product be supplied by more than one supplier? And why do you have a Pivot Model?

b_f's avatar
Level 1

@tykus A product can be supplied by one supplier only. A Supplier can have many products, so a supplier belongs to many products.

tykus's avatar

@b_f okay in that case a many-to-many relationship is correct,; although I don't know why you need a Pivot Model. Otherwise ,your controller code will work as expected

b_f's avatar
Level 1

@tykus I created because the pivot table has information to use in other places. Also the pivot table uses another database connection.

tykus's avatar

@b_f okay.

So what is your question now? What is/is not working?

b_f's avatar
Level 1

@tykus It's working, the question was if the code inside SupplierController@show is the correct way of loading the data to the view :

return view( 'supplier.show' , [ 
            'supplier' => $supplier , 
            'supplier_products' => $supplier->products
] );
tykus's avatar

@b_f yes; where you have just one Supplier it is perfectly fine to lazily load the products relation like that.

b_f's avatar
Level 1

@MohamedTammam 'your_pivot_table_nam' is the pivot table : ProductSupplierRelation::class , What i have above is the "correct way" ?

MohamedTammam's avatar

@b_f No, why did you create a model for the pivot table.

PS: I answer by assuming it's many-to-many relationship.

b_f's avatar
Level 1

@MohamedTammam I created because the pivot table has information to use in other places. Also the pivot table uses another database connection.

Please or to participate in this conversation.