Based on the code you've provided, it looks like you're on the right track. However, there are a few things we need to ensure for the code to work properly with Livewire, Laravel 10, and Spatie Media Library Pro.
First, make sure you have installed and configured Spatie Media Library Pro correctly. Follow the installation instructions provided by the package.
Next, let's review your Livewire component and Blade view to ensure they are set up correctly.
Livewire Component:
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use Livewire\WithFileUploads;
use Illuminate\Support\Facades\Auth;
use Spatie\MediaLibraryPro\Http\Livewire\Concerns\WithMedia;
class GalleryComponent extends Component
{
use WithFileUploads, WithMedia;
public $galleryphotos = [];
public $selectedCollection = 'public-images';
protected $rules = [
'galleryphotos.*' => 'image|max:1024', // Image, max 1MB
'galleryphotos' => 'max:10' // Max 10 images
];
public function updatedGalleryphotos()
{
$this->validate();
}
public function uploadGallery()
{
$user = Auth::user();
foreach ($this->galleryphotos as $photo) {
$user->addMedia($photo->getRealPath())
->toMediaCollection($this->selectedCollection);
}
$this->reset('galleryphotos');
session()->flash('message', 'Images uploaded successfully.');
}
public function render()
{
return view('livewire.gallery-component');
}
}
Blade View (livewire.gallery-component):
<div>
@if (session()->has('message'))
<div class="alert alert-success">
{{ session('message') }}
</div>
@endif
<form wire:submit.prevent="uploadGallery" enctype="multipart/form-data">
@csrf
<label for="collection">Upload To:</label>
<select id="collection" wire:model="selectedCollection">
<option value="public-images">Public Gallery</option>
<option value="private-images">Private Gallery</option>
</select>
<input type="file" wire:model="galleryphotos" multiple>
@error('galleryphotos.*') <span class="error">{{ $message }}</span> @enderror
<button type="submit">Submit</button>
</form>
</div>
Make sure you have the WithFileUploads trait included in your Livewire component to handle file uploads properly.
Also, ensure that your Gallery model is set up correctly to handle media collections as you've defined in your initial code.
Lastly, check your Livewire component's namespace and class name to ensure they match what you're referencing in your Blade view. In the example above, I've named the component GalleryComponent and placed it in the App\Http\Livewire namespace. Adjust your Blade view accordingly if you use a different name or namespace.
If you follow these steps and ensure that all configurations are correct, your user image gallery should work as expected. If you encounter specific errors, please provide the error messages for further assistance.