0
votes

in my Laravel project i get this database structure:

Products

  • Id
  • Name

Orders

  • Id
  • Total

Order_Product

  • Product_id (nullable)
  • Order_Id
  • Details

In my Order model I make belongsToMany retaltionship with Product model:

public function products() {
     return $this->belongsToMany(Product::class)->withPivot('Details');
}

The Problem is when I try to get the Order Products Collection

$order->products();

I don't get rows with nullable product_id, Any solution please ? Thank you.

2
That's how it should work, you that product_id doesn't reference any record in the products table. Are you trying to get all of the pivot table records?MyLibary
Hi, thank you for your response, yes exactly I want to get all pivot table records, did you know how please ?Malek Ben el ouafi
You want to get all of the records as a Product instance? or you don't mind getting it as array?MyLibary
Yes as a Product instance.Malek Ben el ouafi

2 Answers

0
votes

Laravel support "Null Object Pattern" since version 5.5 which allows you to define a default model that will be returned if the given relationship is null.

Try using the following code:

public function products() {
     return $this->belongsToMany(Product::class)->withDefault()->withPivot('Details');
}
0
votes

Most likely, you don't get "nullable" products because you have a relation Order->Products. When you call $order->products(), eloquent tries to get all Product entities that are connected to your Order via product_id field. So, if field is empty, then you can't get Product because there is no connection. One of the solutions is:

  1. create another entity like OrderLine(Order_Product table); add methods like $orderLine->details() and relation to Product like $orderLine->product()
  2. add relation to OrderLine inside Order - $order->line() or $order->info() etc. -> Order hasMany OrderLine
  3. then use $order->line() to get an order's details and products (if exists)

p.s. I've compiled it in my head so it might need some code adjustments. Good luck