Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here
Tutorial Free

How to Add Soft Deletes to Every Model/Migration By Default?

October 05, 2022
2 min read

I'm a big fan of using Soft Deletes functionality for pretty much all Eloquent models. Just in case. Too many times I had clients asking me to restore the "deleted" information. So, how to automate that process a bit?

Generally, how do we add Soft Deletes? By adding a Trait into the Model:

use Illuminate\Database\Eloquent\SoftDeletes;
 
class Task extends Model
{
use SoftDeletes;
}

Also, we need to add the deleted_at to the migration:

Schema::create('tasks', function (Blueprint $table) {
$table->id();
// ... other fields
$table->timestamps();
$table->softDeletes(); // THIS ONE
});

Now, how can we ensure that whenever we run php artisan make:model and php artisan make:migration, the new files would contain those changes?

We can customize the default so-called Stub files that are the foundation of what is generated.

Run this artisan command:

php artisan stub:publish

It would copy the files from the /vendor folder into the new folder called /stubs. Among those files, we are interested in everything around Models and Migrations.

stubs/migration.create.stub:

// ... other code
 
public function up()
{
Schema::create('{{ table }}', function (Blueprint $table) {
$table->id();
$table->timestamps();
});
}

So, all we need to do is add the third line here:

public function up()
{
Schema::create('{{ table }}', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->softDeletes();
});
}

Same thing with the Model stub file.

stubs/model.stub:

namespace {{ namespace }};
 
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
 
class {{ class }} extends Model
{
use HasFactory;
}

After adding the SoftDeletes:

namespace {{ namespace }};
 
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
 
class {{ class }} extends Model
{
use HasFactory, SoftDeletes;
}

And that's it: now try to run php artisan make:model SomeModel -m and enjoy the model/migration with Soft Deletes.

Enjoyed This Tutorial?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Comments & Discussion

T
Taboritis ✓ Link copied!

Good idea. Thank you. Small PSR-12 fix.

Each individual trait that is imported into a class MUST be included one-per-line and each inclusion MUST have its own use import statement.

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.