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:
1use Illuminate\Database\Eloquent\SoftDeletes;2 3class Task extends Model4{5 use SoftDeletes;6}
Also, we need to add the deleted_at
to the migration:
1Schema::create('tasks', function (Blueprint $table) {2 $table->id();3 // ... other fields4 $table->timestamps();5 $table->softDeletes(); // THIS ONE6});
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:
1php 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:
1// ... other code2 3public function up()4{5 Schema::create('{{ table }}', function (Blueprint $table) {6 $table->id();7 $table->timestamps();8 });9}
So, all we need to do is add the third line here:
1public function up()2{3 Schema::create('{{ table }}', function (Blueprint $table) {4 $table->id();5 $table->timestamps();6 $table->softDeletes();7 });8}
Same thing with the Model stub file.
stubs/model.stub:
1namespace {{ namespace }};2 3use Illuminate\Database\Eloquent\Factories\HasFactory;4use Illuminate\Database\Eloquent\Model;5 6class {{ class }} extends Model7{8 use HasFactory;9}
After adding the SoftDeletes:
1namespace {{ namespace }}; 2 3use Illuminate\Database\Eloquent\Factories\HasFactory; 4use Illuminate\Database\Eloquent\Model; 5use Illuminate\Database\Eloquent\SoftDeletes; 6 7class {{ class }} extends Model 8{ 9 use HasFactory, SoftDeletes;10}
And that's it: now try to run php artisan make:model SomeModel -m
and enjoy the model/migration with Soft Deletes.
No comments or questions yet...