user3844579 user3844579 - 21 days ago 6
PHP Question

Laravel withtrashed in a relationship

I have an Order model and a Service model.

An order can be deleted (soft delete).
I want to list all orders, deleted and active and the service that it belongs to.

Order Model:

class Order extends Model
{
use SoftDeletes;

protected $dates = ['deleted_at'];

public function service ()
{
return $this->belongsTo('Service');
}
}


Service Model:

class Service extends Model
{
public function order()
{
return $this->belongsToMany('Order');
}
}


What I tried:

$company=Company::with('orders.service'=>function ($query) {
$query->withTrashed();
},'services'])->where('id',$company->id)->get();


But this returns no orders (and right now I only have 1 deleted order in my db)

Any ideas?

Thanks!!

Answer

you can use

 public function order() {
     return $this->belongsToMany('Order')->withTrashed();
 }