Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use custom soft deleted column in laravel

I know that How can I use Soft Deleting feature for models in laravel. like this :

class Flight extends Model
{
    use SoftDeletes;

    protected $dates = ['deleted_at'];
}

But I want to use a custom column named sender_deleted_at for that feature where all related methods like forceDelete , restore , withTrashed and etc work based that column.

I wrote this Question But I could not get the right answer.

I'm using Laravel 5.3.

like image 381
A.B.Developer Avatar asked Feb 05 '17 07:02

A.B.Developer


People also ask

How use soft delete in laravel?

The feature that you are looking for is soft-deleting in Laravel. You can simply add a new database column to your Laravel Model and use the SoftDeletes trait on your model. After that,you are good to go and soft deletes work instantly.

Why use soft delete in laravel?

Soft deleting the data allows us to easily view and restore the data with minimal work and can be a huge time saver when data is accidentally deleted. Laravel provides support for soft deleting using the Illuminate\Database\Eloquent\SoftDeletes trait.


1 Answers

The SoftDeletes trait uses this code to "delete" a row:

protected function runSoftDelete() {
        $query = $this->newQueryWithoutScopes()->where($this->getKeyName(), $this->getKey());
        $this->{$this->getDeletedAtColumn()} = $time = $this->freshTimestamp();
        $query->update([$this->getDeletedAtColumn() => $this->fromDateTime($time)]);
}

The body of getDeletedAtColumn() is:

public function getDeletedAtColumn() {
    return defined('static::DELETED_AT') ? static::DELETED_AT : 'deleted_at';
}

Therefore you can do this:

class Flight extends Model
{
    use SoftDeletes;    
    protected $dates = ['my_deleted_at'];
    const DELETED_AT = 'my_deleted_at';
}
like image 121
apokryfos Avatar answered Oct 15 '22 15:10

apokryfos