Search code examples
amazon-s3laravel-8laravel-medialibrary

Problem storing laravel-medialibrary-pro media to AWS S3


I feel like I must be missing something very simple but I've lost track of everything I've tried over the past 3 days... I'm using medialibrary-pro for the temporary upload functionality on attachment to upload direct to S3.

First, my configs:

.env

MEDIA_DISK="s3-media"

config/filesystems.php has my s3 disk defined:

        's3-media' => [
        'driver' => 's3',
        'key' => env('AWS_ACCESS_KEY_ID'),
        'secret' => env('AWS_SECRET_ACCESS_KEY'),
        'region' => env('AWS_DEFAULT_REGION'),
        'bucket' => env('AWS_BUCKET'),
        'url' => env('AWS_URL'),
        'endpoint' => env('AWS_ENDPOINT'),
        'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false),
        'root' => 'media-manager'
    ],

media-library.php is stock generated by artisan, the disk name you can see above is set in my .env file:

return [
'temporary_file_upload' => [
    'rules' => 'file|mimes:png,jpg,jpeg,gif|max:2048',
    'disk' => 's3-media',
    ],
];

My form blade view contains:

<x-media-library-attachment name="media" rules="mimes:png,jpg,jpeg,gif|max:2048"/>

My controller has:

$media
   ->addFromMediaLibraryRequest( $request->get('media') )
   ->toMediaCollection('user-media', 's3-media');

And now what happens...

  1. I drag an image over to the attachment container on the form view, it appears to complete successfully and I see the thumbnail of the image I just selected.
  • The attachment uploads directly to S3 and I confirm it's there.
  • The temporary_uploads table shows a model fo the upload.
  • The media table shows a model for the upload with the model_type as TemporaryUpload and the collection_name as default.
  1. Now I click the submit on my form. and get the following exception:

    fopen(/srv/users/username/apps/app-name/storage/media-library/temp/HSutOfGcDuysxkxNRJwMYo42L5RaclTU//file_name.jpg): Failed to open stream: No such file or directory

  • The temporary_uploads table has the model deleted.
  • The media table is updated showing model_type is MediaManager and collection_name is user-media, both as expected.
  • BUT the files are now completely gone from S3. Nothing in storage/media-library or storage/media-library/temp either.

Any suggestions and help is greatly appreciated!


Solution

  • Seems like running save() on your model causes all sorts of problems. I went back to the example code at https://github.com/spatie/laravel-medialibrary-pro-app and rewrote my queries to use the create method rather than an insert. As soon as I took the $model->save() out of the equation everything worked as expected. I ended up creating a local media disk for the temp uploads and then when I process the upload I send it over to my s3-media disk.