luddinus's avatar

Ideas for a "upload files" package

Hi,

I want to make a package that when you set an Eloquent model attribute's to an UploadedFile, it handles the file (upload or delete if is null) and saves the path in the database field.

e.g. user has an avatar, avatar field in database is an string that stores the path of that file.

// some controller
public function update($userId, Request $request)
{
   $user = User::findOrFail($userId);

   $user->update([
      'name' => 'Luddinus',
      'avatar' => $request->file('avatar')
   ]);

   return $user;
}

My Idea is to make an interface with one method (fileables) with returns an array of fields that have files.

Then, for handle automatically the uploads etc., I'm thinking in this way:

  1. Make a trait and with a booteable method:
interface Fileables {
    public function fileables();
}

trait HandlesFiles {
   public static function bootHandlesFiles()
   {
      static::saving(function($model) {
         // get fields that has changed ($model->getDirty())
        // intersect with array_keys($model->fileables())
        // check if the value is an instanceof UploadedFile
        // upload the file and set the value to the path that has been uploaded
      });

      static::deleting(function($model) {
         // delete the files of the model
      });
   }
}

class User extends Model implements Fileables {
   use HandlesFiles;

   protected $fillable = [
      // ...
      'avatar'
   ];

   public function fileables()
   {
      return ['avatar' => 'somePathAndOptions'];
   }
}

What do you think this approach? Other ways? Of course in the future, in "fileables" options I'd handle the thumbnails using intervention/image.

Thx.

0 likes
2 replies

Please or to participate in this conversation.