Reputation: 203
[Help] I need when deleting a record it will also create a deleted_by value.
[company table]
| name | created_by | updated_by | deleted_by | created_at | updated_at | deleted_at |
public static function boot()
{
static::creating(function($company)
{
$company->created_by = Auth::user()->id;
});
}
This will fill created by with the user id when we creating record.
But when I use this when delete record ( using soft delete )
public static function boot()
{
parent::boot();
static::deleting(function($company)
{
$company->deleted_by = Auth::user()->id;
});
}
this method is doesn't work, deleted_by column is not update.
How to fill deleted_by with user id when we delete a record ?
Thanks before
Upvotes: 2
Views: 594
Reputation: 13457
At the moment, Laravel's delete()
method does not take other attribute changes into consideration when it creates the relevant UPDATE
query. Here's a snippet from Eloquent\Model::performDeleteOnModel()
:
$query = $this->newQuery()->where($this->getKeyName(), $this->getKey());
if ($this->softDelete)
{
$this->{static::DELETED_AT} = $time = $this->freshTimestamp();
$query->update(array(static::DELETED_AT => $this->fromDateTime($time)));
}
else
{
$query->delete();
}
Because of the newQuery()
, no changes made to the object are taken into consideration when building the actual DB query.
You could extend the Model class and add in your own functionality to accept any changed attributes, or you can simply toss $company->save()
in your static::deleting()
closure. It will perform two queries, but will take you mere seconds to implement, compared to the first option. Your choice!
Upvotes: 1