File upload
A single or multiple file upload field with a drag-and-drop zone, progress and a list with previews.
zb:file-upload zubazar/ui-pro
This component is in Zubazar UI Pro; Zubazar UI Pro brings Zubazar UI with it. Installing Zubazar UI Pro →
Basic usage
Pass the Livewire property the file is uploaded to with model.
<zb:file-upload model="id_document" label="Identity document" accept=".pdf,image/*" hint="Front of the ID card · PDF or image" />
| Prop | Values |
|---|---|
model | Livewire property (WithFileUploads) |
label | Label above the field |
title | Heading in the zone; default "Drop the file here" |
hint | Description; written from the limits when not given |
Multiple upload and limits
With multiple, several files can be chosen; accept, max-size-kb and max-files are checked in the browser.
<zb:file-upload model="documents" multiple accept=".pdf,.jpg,.png" :max-size-kb="2048" :max-files="5" label="Ticket documents" />
| Prop | Values |
|---|---|
multiple | true | false |
accept | .pdf,.jpg | image/* | application/pdf |
max-size-kb | Per-file limit in KB |
max-files | Maximum number of files in the list (including saved ones) |
Saved files (edit form)
Pass previously saved files with existing; they appear in the same list as new files.
<zb:file-upload
model="documents"
multiple
:max-files="5"
:existing="$savedDocuments"
remove-existing="removeSavedDocument"
/>
| Prop | Values |
|---|---|
existing | [['id' => 7, 'name' => …, 'url' => …, 'size' => …, 'thumbnail' => …]] |
remove-existing | Livewire method called with the id |
Livewire component
Use WithFileUploads in the component, define a property with the same name as model, and move the files to the permanent disk with store() when saving.
use App\Models\Ticket;
use Illuminate\Support\Facades\Storage;
use Livewire\Component;
use Livewire\WithFileUploads;
class TicketDocuments extends Component
{
use WithFileUploads;
public Ticket $ticket;
/** @var array<int, \Livewire\Features\SupportFileUploads\TemporaryUploadedFile> */
public array $documents = [];
/** @var array<int, int> Saved documents to delete on save */
public array $toDelete = [];
protected function rules(): array
{
return [
// 5 documents in total: saved ones count, the ones to delete do not.
'documents' => ['array', 'max:'.max(0, 5 - $this->saved()->count())],
'documents.*' => ['file', 'mimes:pdf,jpg,png', 'max:2048'],
];
}
public function updatedDocuments(): void
{
$this->validate(['documents.*' => $this->rules()['documents.*']]);
}
public function removeSavedDocument(int $id): void
{
$this->toDelete[] = $id;
}
public function save(): void
{
$this->validate();
$this->ticket->documents()->whereKey($this->toDelete)->get()->each->delete();
foreach ($this->documents as $document) {
$this->ticket->documents()->create([
'name' => $document->getClientOriginalName(),
'path' => $document->store('tickets/'.$this->ticket->id, 'public'),
'size' => $document->getSize(),
]);
}
$this->reset('documents', 'toDelete');
}
private function saved()
{
return $this->ticket->documents()->whereKeyNot($this->toDelete);
}
public function render()
{
return view('livewire.ticket-documents', [
'savedDocuments' => $this->saved()->get()->map(fn ($document) => [
'id' => $document->id,
'name' => $document->name,
'url' => Storage::disk('public')->url($document->path),
'size' => $document->size,
]),
]);
}
}
Classic form (without Livewire)
With name instead of model, the files go to the server when the form is submitted; the form must have enctype="multipart/form-data".
<form method="POST" action="{{ route('tickets.update', $ticket) }}" enctype="multipart/form-data" class="space-y-4">
@csrf
@method('PUT')
<zb:file-upload name="attachments" multiple accept=".pdf,.jpg,.png" :max-size-kb="2048" :max-files="5" :existing="$savedAttachments" removed-name="removed_attachments" />
<zb:button type="submit">Save</zb:button>
</form>
| Prop | Values |
|---|---|
name | Form field; [] is appended when multiple |
removed-name | Hidden field for the ids of removed saved files |
About
In a Livewire component (model) the files are uploaded as soon as they are chosen; in a classic form without Livewire (name) they go when the form is submitted. Besides the default look there are avatar and compact looks.
Props
The values the component takes. What are props and slots?
| Prop | Type | Default | Description |
|---|---|---|---|
model | — | null | Livewire property the files are uploaded to (WithFileUploads); either model or name is required |
name | — | null | Without Livewire: name of the form field; the files are submitted with the form |
multiple | boolean | false | Multiple files |
variant | — | 'default' | 'default' | 'avatar' (single round image) | 'compact' (single line) |
accept | — | '' | Such as '.pdf,.jpg' or 'image/*'; checked in the browser |
max-size-kb | — | null | Per-file limit in KB; checked in the browser |
max-files | — | null | Maximum number of files in a multiple list (including saved ones) |
remaining | — | null | Number of files that can still be added in multiple mode (legacy; use max-files instead) |
existing | — | [] | Saved files: id, name, url, size (bytes), thumbnail |
remove-existing | — | null | Livewire method called with the id when a saved file is removed |
removed-name | — | null | Without Livewire: name of the hidden field for the ids of removed saved files |
sortable | boolean | false | Reordering by dragging and with buttons (multiple) |
sort-method | — | null | Livewire method called with the new order |
batch | boolean | false | Livewire + multiple: the files of one choice go in order in one uploadMultiple request |
label | — | null | Label above the field |
required | boolean | false | Adds * to the label; screen readers hear "required" in the name of the choose button. Write the rule on the server as well |
title | — | null | Heading in the zone; defaults to "Drop the file here" / "Drop files here" |
hint | — | null | Description; written from the limits when not given |
camera | boolean | false | "Take a photo" button on touch devices |
show-errors | boolean | true | Shows model and model.* validation errors |
previews | boolean | true | blob: thumbnails of the chosen images; false shows a file icon (a CSP without blob: in img-src) |
list | boolean | true | The kit's file list; false: the drop area alone (the page shows the files) |
Advanced
Sorting
With sortable, the files in a multiple list are reordered by dragging the handle or with the up/down buttons. Every change dispatches the file-upload-sorted event; if sort-method is given, that Livewire method is called with the new order.
<zb:file-upload model="photos" multiple sortable sort-method="sortPhotos" accept="image/*" :existing="$savedPhotos" />
| Prop | Values |
|---|---|
sortable | true | false (multiple only) |
sort-method | Livewire method called with the new order |
Batch upload
With batch (Livewire and multiple), the files of one choice go together in one $wire.uploadMultiple() request, in the order they were chosen. It is meant for forms that process the files together, e.g. variant images matched in order to the selected variants.
<zb:file-upload model="variant_images" multiple batch accept="image/*" :max-size-kb="2048" label="Variant images" hint="The images are matched in order to the selected variants" />
| Prop | Values |
|---|---|
batch | true | false (Livewire, multiple) |
Avatar
variant="avatar" draws a round picker for a single image, with a preview and "Change" and "Remove" buttons. Pass the saved photo with existing; without a thumbnail, the url becomes the preview.
<zb:file-upload model="profile_photo" variant="avatar" label="Profile photo" :max-size-kb="1024" :existing="$savedPhoto" remove-existing="removePhoto" />
| Prop | Values |
|---|---|
variant | 'default' | 'avatar' | 'compact' |
Compact
variant="compact" is a single-line picker for tight forms that files can also be dropped onto. With multiple, the row shows the number of files and the files are listed below.
<zb:file-upload model="invoice" variant="compact" label="Invoice" accept=".pdf" :max-size-kb="2048" />
Taking a photo
When camera is given, a "Take a photo" button appears on touch devices such as phones and tablets; a photo taken with the rear camera is added straight to the list. The button does not appear on devices used with a mouse.
<zb:file-upload model="return_photo" accept="image/*" camera hint="Photo of the damaged product" />
| Prop | Values |
|---|---|
camera | true | false |
Validation errors
The component shows the model's validation errors itself: a documents error below the field, and an error for one file such as documents.2 on that file's row. If you show the messages on the page yourself, pass :show-errors="false".
<zb:file-upload model="documents" multiple accept=".pdf" :max-files="5" />
| Prop | Values |
|---|---|
show-errors | true | false |
Saving the order
sort-method receives the new order on every sort; write the order of saved files right away and store temporary uploads in the same order on save. Always limit the ids to your own record.
public function sortPhotos(array $order): void
{
foreach ($order as $position => $item) {
if ($item['type'] === 'existing') {
$this->product->photos()->whereKey($item['id'])->update(['position' => $position]);
}
}
// Temporary uploads in the same order too (id = getFilename()).
$uploadOrder = collect($order)->where('type', 'upload')->pluck('id')->flip();
$this->photos = collect($this->photos)
->sortBy(fn ($photo) => $uploadOrder[$photo->getFilename()] ?? PHP_INT_MAX)
->values()
->all();
}
Classic form: controller
Validate on the server: the file type and size should match accept and max-size-kb (the max: rule takes KB); the number of files is calculated by subtracting the saved files from the max-files limit. After a validation error, the browser cannot restore the chosen files; attachments and attachments.* errors are listed below the component.
public function update(Request $request, Ticket $ticket): RedirectResponse
{
$removed = $request->input('removed_attachments', []);
$remaining = 5 - $ticket->attachments()->whereKeyNot($removed)->count();
$request->validate([
'attachments' => ['array', 'max:'.max(0, $remaining)],
'attachments.*' => ['file', 'mimes:pdf,jpg,png', 'max:2048'],
'removed_attachments' => ['array'],
'removed_attachments.*' => ['integer'],
]);
$ticket->attachments()->whereKey($removed)->get()->each->delete();
foreach ($request->file('attachments', []) as $attachment) {
$ticket->attachments()->create([
'name' => $attachment->getClientOriginalName(),
'path' => $attachment->store('tickets/'.$ticket->id),
'size' => $attachment->getSize(),
]);
}
return back();
}
Upload state and events
Since the component dispatches Livewire's upload events (livewire-upload-start, -finish, -error) itself, wire:loading and wire:target work with the model name; you can lock the save button until the queue finishes. If the file-upload-reset event is dispatched on the window with { model } ({ name } in a classic form), the running upload is cancelled and waiting and failed rows are cleared (e.g. when a modal closes).
<zb:file-upload model="documents" multiple />
<div class="mt-4 flex justify-end gap-2">
<zb:button variant="white" x-data x-on:click="$dispatch('file-upload-reset', { model: 'documents' })">Cancel</zb:button>
<zb:button wire:click="save" wire:loading.attr="disabled" wire:target="documents,save">Save</zb:button>
</div>
| Prop | Values |
|---|---|
file-upload-reset | Dispatched on the window; { model: 'documents' } |
file-upload-remove-existing | { model, name, id } |
file-upload-sorted | { model, name, order } |
Uploading without Livewire
To upload with model on a page without a Livewire component, register your own transport (e.g. directly to a storage service). upload returns { promise, cancel } for each file; concurrency is how many files are sent at once.
import { registerFileUpload } from '@zubazar/ui-pro';
document.addEventListener('alpine:init', () => {
registerFileUpload(window.Alpine, {
transport: {
concurrency: 3,
upload(file, { onProgress }) {
const request = new XMLHttpRequest();
const promise = new Promise((resolve, reject) => {
request.upload.onprogress = (event) => onProgress((event.loaded / event.total) * 100);
request.onload = () => (request.status < 300 ? resolve(JSON.parse(request.response).id) : reject(new Error('failed')));
request.onerror = () => reject(new Error('failed'));
request.onabort = () => reject(Object.assign(new Error('cancelled'), { cancelled: true }));
});
const body = new FormData();
body.append('file', file);
request.open('POST', '/uploads');
request.setRequestHeader('X-CSRF-TOKEN', document.querySelector('meta[name=csrf-token]').content);
request.send(body);
return { promise, cancel: () => request.abort() };
},
},
});
});
Fields per file and the drop area alone
The row slot is drawn under every file row, with Alpine's item (key, id, name, size, status) in scope. :list="false" hides the kit's list, so your page shows the files.
<zb:file-upload name="attachments" multiple label="Documents">
<zb:slot:row>
<div class="grid gap-2 sm:grid-cols-2">
<input data-zb-control type="text" x-bind:name="'attachment_names[' + item.key + ']'" x-bind:value="item.name" aria-label="Document name" class="rounded-sm border-line-strong bg-field text-sm">
<select data-zb-control x-bind:name="'attachment_types[' + item.key + ']'" aria-label="Document type" class="rounded-sm border-line-strong bg-field text-sm">
<option value="invoice">Invoice</option>
<option value="delivery-note">Delivery note</option>
</select>
</div>
</zb:slot:row>
</zb:file-upload>
| Prop | Values |
|---|---|
row | Slot; under every row, item in scope |
list | false: the drop area alone |
Developer notes
- The whole zone is a button: a file is dropped, or chosen by clicking or with Enter/Space. While the zone has focus, an image pasted from the clipboard is added too.
- The chosen file shows in the list with its preview or file type icon, its size and its status; on a single-file field a new file replaces the previous one.
- There is no Livewire on this page, so the upload is simulated; a file with "hata" in its name shows the error row.
- In a multiple upload each file is uploaded separately with its own progress bar. Queued files wait as "Waiting"; a running transfer can be cancelled, and a failed or cancelled one retried.
- A file that breaks a limit is not uploaded and shows in the list with the reason (e.g. "too large (at most 2 MB)"). The browser check is only quick feedback; write the same rules on the server too.
- A saved file's name opens in a new tab, and saved files count toward the
max-fileslimit. The remove button dispatches thefile-upload-remove-existingevent; ifremove-existingis given, that Livewire method is also called with the id. - A
urlinexistingmust be an http(s) or in-app address; otherwise the file name is not a link. Athumbnailmay also be a small inline image (data:image/png;base64,…, not SVG) or a CDN address in the//hostform. - The
orderitems are{ type: 'existing', id }for a saved file and{ type: 'upload', id }for a temporary upload (idis the file'sgetFilename()value). In a form without Livewire, the files are added to the form field in list order. - A
batchset is appended to the property like single uploads (an array or Collection grows, anullproperty becomes the set itself). Theupdatedhook sees the set at once; if you empty the property in the hook, only the new set arrives each time. - In a batch upload the rows share one progress; cancel and errors affect the whole set, and a retry sends the remaining files together again. A file removed from a set still waiting leaves the set; a file removed while it is being sent cancels the set.
- On the avatar, the upload percentage appears over the image; without
accept,image/*is used, andmultipleis ignored. - On a single-file field the error appears directly on the file row;
documents.2is the file at index 2 of the Livewire property. - For a multiple field make the property an empty array (
public array $documents = []); each file is uploaded separately and added to it. - Files first go to Livewire's temporary folder; validation in the
updatedhook shows the error on the file's row as soon as the upload finishes. Reset the property after saving; the list follows the server, so it empties by itself. - For a temporary file removed from the list, the component calls
$wire.removeUpload()(on a single-file field it sets the property tonull); no separate method is needed. - In a classic form the files are kept in a hidden
<input type="file" name="attachments[]">field; the list can be edited before submitting, and changes reach the field at once. - The ids of removed saved files go in hidden fields named with
removed-name(removed_attachments[]); when the form is reset (reset), the list is cleared too. - In your own transport the promise resolves with the file's id; if it is rejected with an error carrying
cancelled: true, the row is marked as cancelled. With Livewire the files go one after another, since Livewire handles uploads to the same property one by one. - In a classic form bind the name of the field inside
rowto the file's key withx-bind:name; in Livewire write e.g.x-on:change="$wire.set('documents.' + item.id + '.name', $event.target.value)". - Add
data-zb-controlto the fields you write; they get the kit's form field look.
Events
| Event | detail | Description |
|---|---|---|
file-upload-remove-existing | { model, name, id } | Sent from the component when a saved (existing) file is removed from the list; it bubbles. |
file-upload-sorted | { model, name, order } | Sent when the order changes. order is an array of { type: 'existing', id }, { type: 'new', name } or { type: 'upload', id }. |
file-upload-reset (listens) | { model } | { name } | Dispatched on window, it cancels running uploads and clears queued and failed rows. |