As most of the laravel developers, I fell in love with laravel as soon as I started using back in 2013. Since then it has been a great journey. I have built many apps using laravel including “enrolmart“.
Today, I wanted to talk a bit more about the SoftDelete feature of laravel. It is an amazing feature and comes in quite handy when you are building large scale complicated apps. SoftDelete will allow you to delete models without actually deleting it from the database. You can query the deleted models and restore a model any time you want. This really good for apps and models with relationships and deleting the related model sometimes may cause your application to crash.
To use softdeltes in your model:
if it is an existing application, you should create a new migration and if it is a new application or you are creating a new model, you can add this to your migration file:
1 2 3 4 5 6 7 8 |
Schema::create('table', function (Blueprint $table) { //..... $table->softDeletes(); //..... } |
and then update your Model to use the softDeletes trait:
1 2 3 4 5 6 |
class Product extends Model implements Event { use softDeletes; //..... } |
and then update the relationships where you need to display the related model even if they have been deleted:
1 2 3 4 5 6 7 8 9 10 11 |
class Order extends Model implements Event { use softDeletes; //..... public function products() { $this->hasMany(App\Product::class)->withTrashed(); } } |
And now you should be able to query orders even after the product has been deleted as it was no longer required.
Good luck :).
I like this site, useful stuff on here : D.
good stuff. I will make sure to bookmark your blog. https://php665.com/