Best Practice For Get Specific Image On Multi File Attachments In Octobercms

- 1 answer

my system;

I use my octobercms website as a service for my mobile app. Mobile users take multiple photos and save them on their own account. For this, I associate each user with their photos with "file attachments relationship" in the my user model.

public $attachMany = [
    'photos' => 'System\Models\File'

when they(users) want to update one of the photos;

I loop all the photos of that user. If I understand that the picture is the correct one using the if condition, I am changing it.

foreach ($model->photos as $photo) {
    if ( is $photo correct photo ) {
       // update process

my question

To avoid looping all images with foreach;

Is there a method like adding a key during saving process and then taking the photo with that key? Or what is the best practice of this process.



You can simply utilize image ID for that. when you make attachMany relation and if you do $model->photos it will return you a collection of items(files) with its id. please check attached screenshot.

enter image description here

Now, when you show images to your phone app you can also attach that key (ID) to images and when user change image, with image data you can send image ID too

// on server side now you can simply find that image using
$photo = $model->photos()->find(<<-ID->>);
if($photo) {
    // if we have $photo then its correct one
    // now, update $photo
else { // wrong photo id for that user }

Note: please do not go directly like System\Models\File::find(ID) as it will allow user to update any image. $model->photos()->find(ID) ensures that photo of that $model(user) is only accessible.

if any doubt please comment.