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.
Good idea. Thank you. Small PSR-12 fix.