Slug duplicated with soft trashed items

OctoberCMS provide a simple way for generate unique slug (see documentation) but when he check if the slug was already used he dosen't check in soft deleted items.

If in your DB you have defined that the slug field is unique you will get an error message like (like below) when you will try to save an item with the same slug that a soft deleted item.

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry

For solve that simply add the following function to your model and replace slug by the name of the slugged field.

public function beforeDelete()
{
    if ($this->isSoftDelete()) {
        $this->slug = uniqid('deleted-');
        $this->save();
    }
}

This method will replace the slug by an unique ID when you will soft delete an item. With that no more risk of conflict.

Posted in OctoberCMS on Jun 16, 2017