Kartsa
4 months ago
656
4
Laravel

Pivot model deleted-event not including the id-attribute

Posted 4 months ago by Kartsa

I have models Shop, Product and ProductShop pivot table model. I'm using soft deletes and Laravel Auditing to audit all changes. I'm also using a package (ddzobov/laravel-pivot-softdeletes) to enable soft deletes on pivot tables.

The problem isn't really in the packages I'm using, but Laravel Auditing doesn't get the id of the pivot model when it's deleting. So I made a test and it seems that the model instance passed to the deleted-event is incomplete. It only contains the relationship id-columns. Is there any way to make it pass the full model, with the id-attribute?

Here's what I have for testing.

Shop:

namespace App;

use DDZobov\PivotSoftDeletes\Model;

class Shop extends Model
{
    protected $guarded = [];

    public function products()
    {
        return $this->belongsToMany('App\Product')
            ->using('App\ProductShop')
            ->withTimestamps()
            ->withSoftDeletes();
    }
}

Product:

namespace App;

use DDZobov\PivotSoftDeletes\Model;

class Product extends Model
{
    protected $guarded = [];

    public function shops()
    {
        return $this->belongsToMany('App\Shop')
            ->using('App\ProductShop')
            ->withTimestamps()
            ->withSoftDeletes();
    }
}

ProductShop:

namespace App;

use DDZobov\PivotSoftDeletes\Relations\Pivot;

class ProductShop extends Pivot
{
    public $incrementing = true;

    public static function boot()
    {
        parent::boot();

        static::created(function ($model) {
            dd($model);
        });

        static::deleted(function ($model) {
            dd($model);
        });
    }
}

And when I'm testing in tinker...

the created-method has the id:

>>> $shop->products()->attach($product);

App\ProductShop^ {
  #attributes: array:5 [
    "product_id" => 1
    "shop_id" => 1
    "created_at" => "2020-02-24 10:06:22"
    "updated_at" => "2020-02-24 10:06:22"
    "id" => 55
  ]
}

but deleted-method doesn't:

>>> $shop->products()->detach($product);

App\ProductShop^ {
  #attributes: array:2 [
    "shop_id" => 1
    "product_id" => 1
  ]
}

However, in normal models (non-pivot), also the deleted-method has the id. Why is that and how can I include the id on the $model passed to deleted-method in pivot models?

Please sign in or create an account to participate in this conversation.