Reputation: 459
I have set up a fresh Laravel 10. Use Laravel Sail for my environment. I added the basic Spatie Media Library package. In my TestModel I have implemented HasMedia and added the InteractsWithMedia Trait.
My blade
<form method="POST" action="{{ route('test.upload', $test->id) }}" enctype="multipart/form-data">
<input type="file" id="image" name="image" class=">
</form>
My Controller
public function upload(Request $request, Test $test)
{
if($request->has('image')) {
$test->addMedia(($request->image))->toMediaCollection('images');
}
return redirect()->back();
}
I do not receive an error message after the upload and am redirected back as desired. No error is written in the error log either. I should now be able to see the new file in my storage/app/public
folder. But I don't see it. Now I ask myself why? Could it be due to the use of Sail?
Note 1: I have also tried skipping the form and copying a test image from the storage folder. Unfortunately, that doesn't work either. I now suspect that the error may either be in my Sail environment or perhaps in the new Spatie package ("spatie/laravel-medialibrary": "^11.0.0").
Note 2: I have written a file with the Laravel Storage package to test if there is something wrong with the permissions. And it works!
\Illuminate\Support\Facades\Storage::disk('local')->put('example.txt', 'Contents');
dd( $test->addMediaFromRequest('image')->toMediaCollection() );
Spatie\MediaLibrary\MediaCollections\Models\Media {#1273 ▼ // app/Http/Controllers/TestController.php:67
#connection: null
#table: "media"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
+preventsLazyLoading: false
#perPage: 15
+exists: false
+wasRecentlyCreated: false
#escapeWhenCastingToString: false
#attributes: array:11 [▼
"name" => "image-2024-01-08 21-05-00"
"file_name" => "image-2024-01-08-21-05-00.png"
"disk" => "public"
"conversions_disk" => "public"
"collection_name" => "default"
"mime_type" => "image/png"
"size" => 170175
"custom_properties" => "[]"
"generated_conversions" => "[]"
"responsive_images" => "[]"
"manipulations" => "[]"
]
#original: []
#changes: []
#casts: array:4 [▶]
#classCastCache: []
#attributeCastCache: []
#dateFormat: null
#appends: array:2 [▶]
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
+usesUniqueIds: false
#hidden: []
#visible: []
#fillable: []
#guarded: []
#streamChunkSize: 1048576
}
Upvotes: 1
Views: 707
Reputation: 1
I had the same problem as you; it turned out you need to create a new record in your database from the Test model before adding the media.
$test->name = "name";
$test->save();
//then add media
Upvotes: 0