Skip to content

Instantly share code, notes, and snippets.

@alesf
alesf / mastering-text-editors.md
Last active April 14, 2024 19:25
Mastering Text Editors
/*
* This script shows COVID-19 numbers using sledilnik.org API.
* No guarantee on correctness and completeness of the information provided.
*/
const BASE_API_URL = "https://api.sledilnik.org/api";
// URL to open when pressing on the widget.
const WIDGET_PRESS_URL = "https://covid-19.sledilnik.org";
@alesf
alesf / blog.md
Last active September 16, 2023 07:28
Laravel - Eloquent: Cascading delete, forceDelete and restore

If you want to delete a model with related models you can use Laravel model events. There is also a special case if your models cascade.

Lets say you have Folder and File Eloquent models that are related and use SoftDeletes trait and when you delete a folder you also want to delete files in folder and all subfolders with files.

In the boot method or Folder model you catch delete and restore events (actually deleting and restoring events that trigger before restoring or deleting happens). You can delete/restore all files in folder you're deleting/restoring with $folder->files()->delete(); and $folder->files()->withTrashed()->restore();.

Folders on the other hand cascade (folder in a folder in a folder) and because events do not trigger if you don't pull the models (->get() method), the model events won't trigger for subfolders. That's why you need to pull the folders and iterate trough them (->each() method) and delete/restore them.

You could use database CASCADE feature but that does