Eloquent Soft Deletes: Things You May Not Know

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello guys in this lesson we will be talking about soft deletes in eloquent models and it seems like a pretty easy topic but there are quite a lot of hidden things which are not in the docs or maybe not that clear so i will mention all of those in this video so everything i know about soft deletes with examples let's take a look so first a simple example of model posts that include soft deletes and to add soft deletes to your database table there is a migration file with the command soft deletes which adds deleted add timestamp to your database table but did you know there is a separate drop soft delete which you should use in the rollback in the down method of migration if you wish to now in the model you have to of course self-delete straight and then what you can do with that i have a small project here in the list of posts i show all the posts which are not soft deleted because then they automatically are excluded but for example i delete some post of course confirmation for that and then in the database we have three deleted ad posts by this time i had some previous testing so two posts are deleted previously and then how can we view those i've created a separate link view archived posts it adds a get parameter archive which shows only trashed only deleted ad and then you can restore or delete forever restore after confirmation it restores the post here but if we get to archive and delete forever the post will be deleted from the database so now if we refresh the database the record with id number two is totally gone now how does it look in the code in the controller in the list i load post with user because it's eager loading and then when i have the request of archive you can query only trashed so you still have the get but only trashed will transform your query to have where deleted at is not null and then in the index for each of the record i have an if statement so another thing you may not know if post trashed there is a method where you can check if the post is trashed or not so delete it at or not if it is then we can provide two buttons to restore or to force delete that and i have separately two routes but let's start with if it's not trashed then it's a typical post destroyed from resourceful controllers with route model binding to the post and then it gets to the post controller method of destroy pretty simple one and pretty typical one and that delete method doesn't actually delete the record from the database it just adds deleted ad field value but then more interesting things are let's start from the routes web additional two methods on top of route resource and they should be by the way above route resource to avoid any routing conflicts so post restore and post forest delete with the naming of the routes post restore and post force delete they are both route post and then in the index blade we have forms to method post and post restore this time we cannot use route model binding by default because if we do then it wouldn't find the record because it's soft deleted so we need to in the controller do restore and force delete specifically post only trashed so we search only in trashed record find or fail and this will also implement a logic that if the record is not soft deleted then it would fail to find it which is logical i think and then in case of restore we do post restore which empties the deleted add value or in case of force delete it totally deletes it from the table so this is how soft deletes work in a nutshell by default with pretty simple example just one more thing i will show you from the default pretty easy examples is with trashed so you can query the records as default excluding trashed if you don't specify anything then there's only trashed which filters only the trashed obviously and then there's another width trashed like this so with trashed get and let's delete that one and what it will return we refresh the page and we have both deleted records and not deleted records so if for some reason you want to include trashed as well on some page you can specify that with trashed now let's get into a bit more advanced or less known things so be careful if you use soft deletes and you perform the database queries not with eloquent so if you have db table or db query or raw queries or db select something like that that will not use soft delete trade so if you do db table posts with get and then in your database table we have one record deleted ad and i specifically named it archived we refresh the page and it's still visible although it's soft deleted but the database query builder is not the same as eloquent so that self delete is an eloquent trade and if somewhere you use db table or db query directly keep in mind that soft delete would not be enabled then next let's talk about eloquent observers do they work on soft deletes or not let's try to make an observer post observer with the model post and let's see what methods does it have if we open post observer now it handles the created event updated deleted restored and forced deleted so there you go there's the answer if you want to perform some kind of action on restored or force deleted like sending an email like logging something some notification somewhere you have all three methods prepared for you by observer you just need to fill them in with the post details even though it is force deleted at the time that this observer is fired that post is still with the data so you can do something with it next imagine a scenario of validation for unique field and how does deleted ad work then is it included or excluded let's try to create a post with abc title and something something we submit and we have that post at the end right if we try to create the same post with the same title and we have unique validation it will throw an error the title has already been taken so in my form request class in the rules i have unique posts and of course then it throws the validation error which is fine but what if i delete that post so in the table i've soft deleted that post and ordered by the newest post and now if we try to create that post what would happen submit the validation is still fired so by default laravel validation does not really see deleted ad fields but there are two ways how you can do this check and one of them is older and another is from 8.52 in laravel so you can change unique posts to rule unique and post like this and then you can add whatever methods you want for example where deleted at is no and then if we try to create the post again we submit and now the validation is not fired and if we refresh we have another post with abc and with deleted ad null then in laravel 8.52 there was a new thing released by philo hermanns which is just shorter way to ignore trash so instead of that where deleted at no or where no like this you can do just ignore trashed like this now finally let's get into cascading of soft deleted records so imagine a scenario that post belongs to a user so user has many posts and what if you delete the user and both tables use soft deletes what would happen then with the child records by default in laravel when defining the relationship you can define on delete cascade and then what would happen with the parent record if you delete the parent record all the child records will be deleted from the database automatically on the database level on mysql level cleaning up the table what would happen if you use soft delete by default the child records are not soft deleted and here's an example for example we have posts and a few posts belong to the author cassandra and i've built a specific users table with cassandra and let's try to delete it with simple user controller user delete and we click the delete here we approve and then in the database in the users table we have cassandra as refresh soft deleted so it's not in the database of users but if we get back to the posts the posts of cassandra are still here but with author empty so author does not exist but the posts exist so this is how laravel works by default in eloquent with soft deletes but if you do want to cascade soft deletes there are a few packages that can help you probably the most old and the most used one is from michael dorinda cascading soft deletes for a larger framework so installation is just composer require and we copy and paste it like this and all we need to do to enable that soft delete cascade is just add the cascade soft deletes in the parent of the relationship so in the user model in our case so let's open user model and add on top of soft deletes would add cascade soft deletes which comes from the package and then it is added automatically here and then we need to define what to solve delete so cascade deletes the table or the relationship name of posts in our case so post is a relationship name for has many posts this one and let's try it out let's delete another user so we get back to our project mr oli emerick has three posts let's get to the users table i didn't build any navigation so i'm just doing it manually so this one let's delete are you sure okay no errors and if we get back to the posts do we see the post of that author no and in the database we have that mr ole as soft deleted and the posts are soft deleted as well with this timestamp so this is a package that is easy to install easy to use and that can help you to cascade your self-deleted records that's it did you find out anything new about soft deletes shoot in the comments below and if you want to find more about eloquent in general i have a special course called eloquent expert level which is four hours only around eloquent it is an old one because it was released with laravel 5.8 but 95 of that is still relevant i'm planning to renew all of my courses upgrade them in laravel 9 when laravel 9 is released in 2022 but still eloquent course is one of the most stable ones that stood the test of time because eloquent is pretty stable since the beginning that's it for this time and see you guys in other videos
Info
Channel: Laravel Daily
Views: 17,621
Rating: undefined out of 5
Keywords:
Id: ffAt9Np-zEM
Channel Id: undefined
Length: 10min 57sec (657 seconds)
Published: Tue Oct 12 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.