This forum has moved to a new location and is in read-only mode. Please visit talk.octobercms.com to access the new location.
Tschallacka
If you wish to copy an attachMany collection of images from one model, to another model you can use this code.
private function copyImages($source,$destination,$access) {
foreach($source->{$access} as $image) {
if(!$this->checkIfExists($image, $destination->{$access})) {
$tmp = new File();
$tmp = $tmp->fromFile(base_path().DIRECTORY_SEPARATOR.'storage'.DIRECTORY_SEPARATOR.'app'.DIRECTORY_SEPARATOR.$image->getDiskPath());
$tmp->file_name = $image->getFilename();
$tmp->title = $image->title;
$tmp->description = $image->description;
$destination->{$access}()->add($tmp);
}
}
}
private function checkIfExists($img,$destinationcollection) {
foreach($destinationcollection as $image) {
$cutto = strlen($img->getFilename());
$loc = strrpos($img->getFilename(), '[');
if($loc === false) {
$loc = strrpos($img->getFilename(), '.');
}
if($loc !== false) {
$cutto = $loc;
}
$str = substr($img->getFilename(),0,$cutto);
if(strpos($image->getFilename(),$str) !== false) {
return true;
}
}
return false;
}
I use it for example in an ajax handler in the following way:
public function onCopyImagesFromLanguage() {
$source_id = post('source');
$destination_id = post('destination');
$source = \Tschallacka\HotelManager\Models\HotelTranslationModel::find($source_id);
$destination = \Tschallacka\HotelManager\Models\HotelTranslationModel::find($destination_id);
$this->copyImages($source,$destination,'backgroundimage');
return 'success';
}
Last updated
slowpokefarm
In checkIfExists, is there some reason you didn't compare the filename as is? Why searching for substing occurrence instead?
1-2 of 2