jeudi 25 avril 2019

Laravel custom soft delete restore not working properly

Adding new columns deleted_flag tiny integer to the Larave soft delete feature.

trait  CustomSoftDeleteTrait
{
    use SoftDeletes;

    protected function runSoftDelete()
    {
        $query = $this->setKeysForSaveQuery($this->newModelQuery());

        $time = $this->freshTimestamp();

        $columns = [$this->getDeletedAtColumn() => $this->fromDateTime($time)];

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

        if ($this->timestamps && ! is_null($this->getUpdatedAtColumn())) {
            $this->{$this->getUpdatedAtColumn()} = $time;

            $columns[$this->getUpdatedAtColumn()] = $this->fromDateTime($time);
        }

        $columns[$this->getDeletedFlagColumn()] = 1; //<-- here is the deleting

        $query->update($columns);
    }

    protected function restore()
    {            
        if ($this->fireModelEvent('restoring') === false) {
            return false;
        }

        $this->{$this->getDeletedFlagColumn()} = 0; //<-- here is restoring
        $this->{$this->getDeletedAtColumn()} = null;    

        $this->exists = true;

        $result = $this->save();

        $this->fireModelEvent('restored', false);

        return $result;
    }

    public function getDeletedFlagColumn()
    {
        return defined('static::DELETED_FLAG') ? static::DELETED_FLAG : 'deleted_flag';
    }
}

Migration for the model,

Schema::create('families', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->integer('family_type');

            $table->timestamp('create_date')->nullable();
            $table->timestamp('update_date')->nullable();
            $table->timestamp('delete_date')->nullable();
            $table->tinyInteger('delete_flg')->nullable();
        });

Using the custom trait in model,

class Family extends Model
{
    use CustomSoftDeleteTrait;

    protected $guarded = [
        'id',
    ];

    const CREATED_AT = 'create_date';
    const UPDATED_AT = 'update_date';
    const DELETED_AT = 'delete_date';
    const DELETED_FLAG = 'delete_flg';
}

When the model is deleted using $family->delete(), both columns delete_date and delete_flg are set. When the model is restored, only one field delete_date is set to null. The delete_flg field remains unchanged at 1.



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2IVH1Vt
via IFTTT

Aucun commentaire:

Enregistrer un commentaire