3

On my project all models extend BaseModel class, which uses SoftDeletes trait by default. But in some specific cases, e.g. in class ShouldHardDelete I don't want my DB records to be deleted softly. Let's suppose, I can't deny extending BaseModel.

What changes should I make in my ShouldHardDelete class to prevent it from using soft deletes?

4
  • out of curiosity why would you want to completely remove record? Commented Jul 11, 2019 at 5:26
  • @usrNotFound, I will have to insert and delete multiple records (can't simply change them, too complex logic). Soft-deletes are not so necessary for these records, keeping deleted ones in DB would cause too much disk space wasted Commented Jul 11, 2019 at 5:35
  • I think $modal->forceDelete() and would the job Commented Jul 11, 2019 at 5:45
  • That's an option, but that would make me do some exceptional processing if I ever want to delete these objects along with some other soft-deletable ones Commented Jul 11, 2019 at 5:57

2 Answers 2

9

There are two things you should do:

  1. There is a static method bootSoftDeletes() in SoftDeletes trait, which initializes soft-delete behaviour for the model:
    /**
     * Boot the soft deleting trait for a model.
     *
     * @return void
     */
    public static function bootSoftDeletes()
    {
        static::addGlobalScope(new SoftDeletingScope);
    }

Override it in the ShouldHardDelete class to an empty method:

    /**
     * Disable soft deletes for this model
     */
    public static function bootSoftDeletes() {}
  1. Set $forceDeleting field to true in ShouldHardDelete:
    protected $forceDeleting = true;

Thus, you can disable soft-deleting behaviour, while still extending BaseModel which uses SoftDeletes trait.

Sign up to request clarification or add additional context in comments.

Comments

3

if you are using softDelete trait but don't want to use it on a specific query then you can do using the withoutGlobalScope method in the model.

User::withoutGlobalScope(Illuminate\Database\Eloquent\SoftDeletingScope::class)->get();

if you want to use multiple models for a specific query then better to extends eloquent builder in AppServiceProvider

public function boot()
{
   Builder::macro('withoutSoftDeletingScope', function () {
     $this->withoutGlobalScope(Illuminate\Database\Eloquent\SoftDeletingScope::class);

       return $this;
    });
 }

and then you can call as a method in any model

User::withoutSoftDeletingScope()->get();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.