Foreign Key events & Laravel Soft Deletes

Never really noticed how great foreign keys were until I started a job that just didn’t have any in the database. That also being said, foreign key events are even nicer to implement and takes a LOT of pressure off the developer to clean up other relationships on deletion.

Need an example of what I’m talking about? I’ve got you covered.

Say you have a survey model and that model has a relationship for questions. Well when a survey gets deleted, the FK event should also fire and delete the questions too. This should only happen by calling $survey->delete();

Turns out that this doesn’t work with Laravel soft deletes.

Soft deletes are sort of a nice feature for devs who work with accidental delete button pushers. All it does is sets a delete timestamp and Laravel auto filters out the deleted models when you’re pulling a collection. It’s great (maybe a database size killer) but turns out it doesn’t take into account the FK events.

Now how do you fix this issue without having to write a bunch of code? I’ve got an answer for you on that too.

Enter Laravel Eloquent events.

On any of the major events (created, saved, delete), you can fire off some additional events without too much overhead.

For my previous example with Surveys, I created this delete event:

public static function boot() {
   parent::boot();

   self::deleting(function (Survey $survey) {
       $survey->questions()->delete();
   });
}

Anytime a survey gets deleted, the questions will too. The questions have additional deleting events that will also fire. Note, when a survey does get deleting, you may have to call a refresh() on it to see the relationships are actually deleted.

There’s your tip for the day!