I'm trying to clean-up the assets in a specific folder that aren't being used at all, i.e. aren't related to anything.

I got the list O.K. just using this

$assets = Asset::find()->volume('artists')->kind('image')->limit(50000)->ids();

$assetsToDelete = [];

foreach($assets as $asset) {
    $results = (new Query())
        ->where(['targetId' => $asset])
        ->orWhere(['sourceId' => $asset])

    if (!count($results)) {
        $assetsToDelete[]  = $asset;

return  $this->asJson($assetsToDelete);

Right now I'm just returning all the ids in an array but I'm hoping to find a command to delete the element AND delete the stored asset on the server

Any ideas?

1 Answer 1


I'm not sure how well it'd go with 50,000 Assets, but you should just be able to call Craft::$app->elements->deleteElement($asset) for each one, or Craft::$app->elements->deleteElementById($asset->id), as seen in the Elements Class Reference.

  • Will that delete the actual file off the server as well? Seems like it would just delete the element in the database Dec 28, 2018 at 14:25
  • @KeithMancuso it'll eventually trigger the asset element's afterDelete method which will take care of deleting the file: github.com/craftcms/cms/blob/master/src/elements/…
    – Brad Bell
    Dec 28, 2018 at 17:16

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.