src/HasMedia/HasMediaTrait.php
public function clearMediaCollectionExcept(string $collectionName = 'default', $excludedMedia = [])
    {
        if ($excludedMedia instanceof Media) {
            $excludedMedia = collect()->push($excludedMedia);
        }

        $excludedMedia = collect($excludedMedia);

        if ($excludedMedia->isEmpty()) {
            return $this->clearMediaCollection($collectionName);
        }

        $this->getMedia($collectionName)
            ->reject(function (Media $media) use ($excludedMedia) {
                return $excludedMedia->where('id', $media->id)->count();
            })
            ->each->delete();

        if ($this->mediaIsPreloaded()) {
            unset($this->media);
        }

        return $this;
    }
public function clearMediaCollectionExcept(string $collectionName = 'default', $excludedMedia = [])
    {
        if ($excludedMedia instanceof Media) {
            $excludedMedia = collect()->push($excludedMedia);
        }

        $excludedMedia = collect($excludedMedia);

        if ($excludedMedia->isEmpty()) {
            return $this->clearMediaCollection($collectionName);
        }

        $this->getMedia($collectionName)
            ->reject(function (Media $media) use ($excludedMedia) {
                return $excludedMedia->where('id', $media->id)->count();
            })
            ->each->delete();

        if ($this->mediaIsPreloaded()) {
            unset($this->media);
        }

        return $this;
    }
public function clearMediaCollectionExcept ( string $ collectionName = 'default' , $ excludedMedia = [ ] ) { if ( $ excludedMedia instanceof Media ) { $ excludedMedia = collect ( ) -> push ( $ excludedMedia ) ; } $ excludedMedia = collect ( $ excludedMedia ) ; if ( $ excludedMedia -> isEmpty ( ) ) { return $ this -> clearMediaCollection ( $ collectionName ) ; } $ this -> getMedia ( $ collectionName ) -> reject ( function ( Media $ media ) use ( $ excludedMedia ) { return $ excludedMedia -> where ( 'id' , $ media -> id ) -> count ( ) ; } ) -> each -> delete ( ) ; if ( $ this -> mediaIsPreloaded ( ) ) { unset ( $ this -> media ) ; } return $ this ; }
Remove all media in the given collection except some.

@param string $collectionName
@param \Spatie\MediaLibrary\Models\Media[]|\Illuminate\Support\Collection $excludedMedia

@return $this
Remove all media in the given collection except some .