How to update field when deleting row in laravel

Suppose I have a table named customer, where the customer table has a field named deleted_by. I implement softDeletein the model customer. Now I want to update deleted_bywhen deleting a row. So that I can trace who removes this line.

I am searching on Google about this, but have not found anything.

I am using laravel 4.2.8 and Eloquent

+4
source share
4 answers

You can update the field using something like this:

$customer = Customer::find(1); // Assume 1 is the customer id

if($customer->delete()) { // If softdeleted

    DB::table('customer')->where('id', $customer->id)
      ->update(array('deleted_by' => 'SomeNameOrUserID'));
}

Alternatively, you can do this in a single request:

// Assumed you have passed the id to the method in $id
$ts = Carbon\Carbon::now()->toDateTimeString();
$data = array('deleted_at' => $ts, 'deleted_by' => Auth::user()->id);
DB::table('customer')->where('id', $id)->update($data);

Both are executed as part of a single request softDeleteand are recorded deleted_by.

+3
source

Something like this is the way:

// override soft deleting trait method on the model, base model 
// or new trait - whatever suits you
protected function runSoftDelete()
{
    $query = $this->newQuery()->where($this->getKeyName(), $this->getKey());

    $this->{$this->getDeletedAtColumn()} = $time = $this->freshTimestamp();

    $deleted_by = (Auth::id()) ?: null;

    $query->update(array(
       $this->getDeletedAtColumn() => $this->fromDateTime($time), 
       'deleted_by' => $deleted_by
    ));
}

:

$someModel->delete();

.

+3

Model Event .

<?php
class Customer extends \Eloquent {
    ...
    public static function boot() {
        parent::boot();

        // We set the deleted_by attribute before deleted event so we doesn't get an error if Customer was deleted by force (without soft delete).
        static::deleting(function($model){
            $model->deleted_by = Auth::user()->id;
            $model->save();
        });
    }
    ...
}

, .

Customer::find(1)->delete();
+1

I know this is an old question, but what you could do (in the client model) is this:

public function delete() 
{
    $this->deleted_by = auth()->user()->getKey();
    $this->save();

    return parent::delete();
}

This will still allow soft deletion when setting a different value immediately before deleting it.

+1
source

All Articles