Laravel Media library pro - Unchanged value of custom properties not persisting

141 Views Asked by At

Using custom properties with media library pro collection in Livewire, only changed values save. Existing, unchanged custom property values are deleted.

  • If I change both properties, they save.
  • If I change neither property, they remain saved.
  • If I change one of the custom properties and not the other, changed one is saved, the other deleted.

I'd expect the unchanged to remain unless specifically cleared. How can I do that?

Code to hydrate:

$this->invoices = $this->model->getMedia('job_invoices');

Code to save:

$this->model
    ->syncFromMediaLibraryRequest($this->invoices)
    ->withCustomProperties('invoice_value', 'invoice_date')
    ->toMediaCollection('job_invoices');

$this->clearMedia('job_invoices');

Custom property blade template:

<div class="media-library-field">
    <label class="media-library-label">Value</label>
    <input
        class="media-library-input"
        type="text"
        {{ $mediaItem->livewireCustomPropertyAttributes('invoice_value') }}
    />
    @error($mediaItem->customPropertyErrorName('invoice_value'))
        <span class="media-library-text-error">
            {{ $message }}
        </span>
    @enderror
</div>

<div class="media-library-field">
    <label class="media-library-label">Date</label>
    <input
        class="media-library-input"
        type="date"
        {{ $mediaItem->livewireCustomPropertyAttributes('invoice_date') }}
        x-on:change.debounce="$wire.setCustomProperty('{{ $mediaItem->uuid }}', 'invoice_date', document.getElementsByName('{{ $mediaItem->customPropertyAttributeName('invoice_date') }}')[0].value)"
    />
    @error($mediaItem->customPropertyErrorName('invoice_date'))
        <span class="media-library-text-error">
            {{ $message }}
        </span>
    @enderror
</div>

Example of data sent when changing one field and not the other:

  "e944d21f-1cf6-4139-b3c1-f7cd9cb114b0" => array:10 [▼
    "name" => "INV-0297"
    "fileName" => "Invoice-INV-0297.pdf"
    "uuid" => "e944d21f-1cf6-4139-b3c1-f7cd9cb114b0"
    "previewUrl" => ""
    "order" => 1
    "customProperties" => array:2 [▼
      "invoice_date" => "2023-01-01"
      "invoice_value" => "123"
    ]
    "extension" => "pdf"
    "size" => 75910
    "createdAt" => 1683887419
    "custom_properties" => array:1 [▼
      "invoice_value" => "1,234"
    ]
  ]

In the above example only the invoice_value changed. The original values can be seen in customProperties.

As an aside, this also effects validation. A field with a value, when saved with no changes will raise a validation error.

0

There are 0 best solutions below