I have the channel entry to which the matrix block belongs and I have the ID of the block itself. Does anybody know the correct approach for deleting the matrix block on the entry?

Context: module (PHP) not template.

1 Answer 1


You can use the Elements service to delete any element, including matrix blocks:

use craft\elements\MatrixBlock;

/** @var craft\services\Elements $elementsService */
$elementsService = Craft::$app->getElements();

$myMatrixBlockId = 123;

// delete a matrix block directly
$matrixBlock = MatrixBlock::find()->id($myMatrixBlockId)->one();
$elementsService->deleteElement($matrixBlock, false);

// delete a matrix block by ID
$elementsService->deleteElementById($myMatrixBlockId, null, null, false);

The second argument to deleteElement (and the fourth argument to deleteElementById) controls if you want a hard delete (true) or a soft-delete (false). A hard delete removes the block from the database completely, while a soft delete keeps it in the database and only marks it as deleted, allowing it to be restored.

  • 1
    Heroic answer, thank you very much!
    – Jake
    Jun 18, 2021 at 15:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.