File Uploads in Livewire 3.0

File Uploads in Livewire 3.0

Step 1: Creating the Livewire Component

We’ll start by creating a new component for handling file uploads:

php artisan make:livewire FileUpload

This command will generate the following files:



app/Livewire/FileUpload.php – The PHP class for the component logic.
resources/views/livewire/file-upload.blade.php – The Blade file for the file upload UI.


This command will generate the following files:

  1. app/Livewire/RegisterUser.php – The PHP class for the component logic.

  2. resources/views/livewire/register-user.blade.php – The Blade file for the form UI.

Step 2: Setting Up the Component Logic

Open the FileUpload.php file and define the property for managing file uploads:


<?php

namespace App\Livewire;

use Livewire\Component;
use Livewire\WithFileUploads;

class FileUpload extends Component
{
    use WithFileUploads;

    public $file;

    protected $rules = [
        'file' => 'required|mimes:jpg,jpeg,png,pdf|max:1024', // Max size: 1MB
    ];

    public function save()
    {
        $this->validate();

        // Store the file
        $filePath = $this->file->store('uploads', 'public');

        session()->flash('success', 'File uploaded successfully: ' . $filePath);

        // Reset the file input
        $this->reset('file');
    }

    public function render()
    {
        return view('livewire.file-upload');
    }
}


Key Points:

  1. WithFileUploads : This trait provides the functionality to handle file uploads in Livewire.

  2. Validation Rules: Restricts the file type to JPG, JPEG, PNG, and PDF, with a maximum size of 1MB.

  3. store() Method:: Saves the file to the storage/app/public/uploads directory.

  4. Flash Messages:: Notifies the user of successful uploads.

Step 3: Building the Form UI

Open the file-upload.blade.php  file and create the file upload form:


<div>
    @if (session()->has('success'))
        <div class="alert alert-success">
            {{ session('success') }}
        </div>
    @endif

    <form wire:submit.prevent="save">
        <div>
            <label for="file">Upload File</label>
            <input type="file" id="file" wire:model="file">
            @error('file') <span class="error">{{ $message }}</span> @enderror
        </div>

        @if ($file)
            <div>
                <p>Preview:</p>
                <img decoding="async" src="{{ $file->temporaryUrl() }}" alt="File Preview" style="max-width: 200px;">
            </div>
        @endif

        <button type="submit">Upload</button>
    </form>
</div>


What’s Happening Here?

  1. wire:model="file": Binds the file input to the $file property in the component.

  2. temporaryUrl(): Generates a temporary URL for previewing the uploaded file before saving it.

  3. wire:submit.prevent="save": Prevents the default form submission and triggers the save() method.

  4. Error Messages: Displays validation errors dynamically using @error

Step 4: File Preview

The temporary URL preview is particularly useful for image uploads. It allows users to see the file they are about to upload. This is achieved using:

$file->temporaryUrl()

Note: This feature is only available for local file uploads and will not work if you’re uploading files directly to external storage (e.g., S3).

Step 5: Handling Large Files

For larger file uploads, you may need to:

  1. Update the  post_max_size  and   upload_max_file size  values in your  php.ini  file.
  2. Configure chunked file uploads in Livewire using the  WithFileUploads  trait.

Step 6: Securing File Uploads

To ensure secure file uploads:

  1. Restrict File Types: Use mimes or  mimetypes  in the validation rules.

  2. Set File Size Limits: Use the  max  validation rule to prevent overly large uploads.

  3. Sanitize File Names: Livewire automatically handles this when using  store().

Final Output

With the above setup, your file upload component will:

    1. Allow users to upload files interactively.

    2. Display real-time validation error messages.

    3. Preview uploaded files before saving them.

    4. Notify users of successful uploads.

Key Features Covered Today

With the above setup, your file upload component will:

      1. Using the WithFileUploads trait for file uploads.

      2. Handling file validations (type, size) in Livewire 3.0

      3. Displaying file previews with temporaryUrl()

      4. Securely storing uploaded files.

      5. Flashing success messages after file uploads.

© Copyright 2025 Wontonee. All Right Reserved.

×How can I help you?