Black Friday: coupon FRIDAY24 for 40% off Yearly/Lifetime membership! Read more here

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

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.

avatar

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.

👍 7
🥳 1

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 67 courses (1172 lessons, total 43 h 18 min)
  • 90 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent New Courses