feat: implement Spatie Media Library integration
with CRUD operations and media management UI
This commit is contained in:
parent
d40b87438d
commit
02884d4e2b
11 changed files with 499 additions and 4 deletions
72
app/Filament/Resources/Media/Pages/EditMedia.php
Normal file
72
app/Filament/Resources/Media/Pages/EditMedia.php
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Media\Pages;
|
||||
|
||||
use App\Filament\Resources\Media\MediaResource;
|
||||
use Filament\Actions\DeleteAction;
|
||||
use Filament\Actions\ViewAction;
|
||||
use Filament\Resources\Pages\EditRecord;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
|
||||
class EditMedia extends EditRecord
|
||||
{
|
||||
protected static string $resource = MediaResource::class;
|
||||
|
||||
protected ?string $uploadedFile = null;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
ViewAction::make(),
|
||||
DeleteAction::make(),
|
||||
];
|
||||
}
|
||||
|
||||
protected function mutateFormDataBeforeSave(array $data): array
|
||||
{
|
||||
// Extract the file data if a new file was uploaded
|
||||
$file = $data['file'] ?? null;
|
||||
unset($data['file']);
|
||||
|
||||
// Only update file-related fields if a new file was uploaded
|
||||
if ($file && $file !== $this->record->getPathRelativeToRoot()) {
|
||||
$this->uploadedFile = $file;
|
||||
|
||||
// Keep the original file_name to prevent breaking existing references
|
||||
// $data['file_name'] is not updated - we preserve the original filename
|
||||
$data['mime_type'] = Storage::disk('public')->exists($file)
|
||||
? Storage::disk('public')->mimeType($file)
|
||||
: 'application/octet-stream';
|
||||
$data['size'] = Storage::disk('public')->exists($file)
|
||||
? Storage::disk('public')->size($file)
|
||||
: 0;
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
protected function afterSave(): void
|
||||
{
|
||||
if ($this->uploadedFile && $this->record) {
|
||||
$disk = Storage::disk('public');
|
||||
$mediaDirectory = (string) $this->record->id;
|
||||
|
||||
// Delete old file if it exists
|
||||
$oldPath = $mediaDirectory.'/'.$this->record->getOriginal('file_name');
|
||||
if ($disk->exists($oldPath)) {
|
||||
$disk->delete($oldPath);
|
||||
}
|
||||
|
||||
// Move new file to Spatie's expected location using the original filename
|
||||
if ($disk->exists($this->uploadedFile)) {
|
||||
$disk->makeDirectory($mediaDirectory);
|
||||
// Use the original file_name to preserve existing references
|
||||
$newPath = $mediaDirectory.'/'.$this->record->file_name;
|
||||
$disk->move($this->uploadedFile, $newPath);
|
||||
}
|
||||
|
||||
// Redirect to the same page to refresh the form state
|
||||
$this->redirect(static::getUrl(['record' => $this->record]), navigate: true);
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue