Malek Ben el ouafi
Malek Ben el ouafi

Reputation: 1025

belongsToMany with nullable foreign - Laravel 5.8

in my Laravel project i get this database structure:

Products

Orders

Order_Product

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.

Upvotes: 0

Views: 738

Answers (2)

Shandur
Shandur

Reputation: 41

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

Upvotes: 0

MyLibary
MyLibary

Reputation: 1771

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');
}

Upvotes: 0

Related Questions