PHPackages                             stalkdeveloper/laravel-file-uploader - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [File &amp; Storage](/categories/file-storage)
4. /
5. stalkdeveloper/laravel-file-uploader

ActiveLibrary[File &amp; Storage](/categories/file-storage)

stalkdeveloper/laravel-file-uploader
====================================

A Laravel package for handling file uploads from both file and URL, saving to Laravel public storage.

v1.0.0(7mo ago)03MITPHPPHP ^8.1

Since Sep 29Pushed 7mo agoCompare

[ Source](https://github.com/stalkdeveloper/laravel-file-uploader)[ Packagist](https://packagist.org/packages/stalkdeveloper/laravel-file-uploader)[ RSS](/packages/stalkdeveloper-laravel-file-uploader/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (4)Versions (2)Used By (0)

Laravel File Uploader
=====================

[](#laravel-file-uploader)

A comprehensive Laravel package for handling file uploads from both local files and URLs, with support for multiple file types, folder organization, and polymorphic relationships. Files are saved to Laravel's storage with customizable folder structures, and metadata is stored in the database for persistent retrieval.

Features
--------

[](#features)

- **Dual Input Methods**: Upload files from local device or download from URLs
- **Multiple File Types**: Images, videos, PDFs, documents, Excel files, audio, archives, or any file type
- **Folder Organization**: Organize files in custom folder structures
- **Polymorphic Relationships**: Files can belong to any model (Users, Posts, Products, etc.)
- **Configurable Limits**: Customizable file size limits and validation rules
- **Robust Validation**: Comprehensive validation for file types, sizes, and URL accessibility
- **Security**: Path sanitization and MIME type verification
- **Flexible Naming**: Multiple file naming strategies (random, original, timestamp)
- **Error Handling**: Clear error messages for invalid files or URLs

Supported File Types
--------------------

[](#supported-file-types)

CategorySupported FormatsImagesjpg, jpeg, png, gif, webp, bmp, svgVideosmp4, mkv, avi, mov, webmDocumentspdf, doc, docx, xls, xlsx, ppt, pptx, txt, rtfExcelxls, xlsx, csvAudiomp3, wav, ogg, aac, flacArchiveszip, rar, 7z, tar, gzAnyAll supported formats combinedRequirements
------------

[](#requirements)

- PHP ^8.1
- Laravel ^9.0, ^10.0, ^11.0, or ^12.0

Installation
------------

[](#installation)

Install the package via Composer:

```
composer require stalkdeveloper/laravel-file-uploader
```

Publish the configuration file:

```
php artisan vendor:publish --tag=file-uploader-config
```

Publish and run migrations:

```
php artisan vendor:publish --tag=file-uploader-migrations
php artisan migrate
```

Create storage symlink (if using public disk):

```
php artisan storage:link
```

Configuration
-------------

[](#configuration)

The configuration file is located at `config/file-uploader.php`. Key options:

```
return [
    'storage' => [
        'disk' => 'public',      // Storage disk
        'path' => 'files',       // Base storage directory
        'url_path' => 'storage/files',
    ],

    'defaults' => [
        'max_size' => 5120,      // 5MB default
        'file_type' => 'any',
    ],

    'file_types' => [
        'image' => [
            'mimes' => ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'svg'],
            'max_size' => 5120,  // 5MB
        ],
        'video' => [
            'mimes' => ['mp4', 'mkv', 'avi', 'mov', 'webm'],
            'max_size' => 51200, // 50MB
        ],
        // ... more file types
    ],

    'validation' => [
        'url' => [
            'timeout' => 60,
            'user_agent' => 'Laravel File Uploader/1.0',
        ],
    ],

    'database' => [
        'table' => 'files',
        'model' => \StalkArtisan\LaravelFileUploader\Models\File::class,
    ],

    'naming' => [
        'strategy' => 'random', // random, original, timestamp
        'length' => 40,
    ],
];
```

Usage
-----

[](#usage)

### 1. Add Trait to Your Model

[](#1-add-trait-to-your-model)

```
namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use StalkArtisan\LaravelFileUploader\Traits\HasFileUploads;

class User extends Authenticatable
{
    use HasFileUploads;
}

class Post extends Model
{
    use HasFileUploads;
}
```

### 2. Basic File Upload

[](#2-basic-file-upload)

#### Using the Trait (Recommended)

[](#using-the-trait-recommended)

```
// Upload local file
$file = $user->uploadFile($request->file('avatar'), 'image');

// Upload from URL
$file = $user->uploadFile('https://example.com/image.jpg', 'image');

// With custom size limit (10MB)
$file = $user->uploadFile($request->file('document'), 'pdf', 10240);
```

#### Using Facade Directly

[](#using-facade-directly)

```
use StalkArtisan\LaravelFileUploader\Facades\FileUploader;

$file = FileUploader::upload($request->file('file'), 'image');
$file = FileUploader::uploadFromUrl('https://example.com/file.pdf', 'pdf');
```

### 3. Advanced Usage with Folder Structure

[](#3-advanced-usage-with-folder-structure)

```
// Upload to specific folder
$file = $user->uploadFile(
    $request->file('avatar'),
    'image',
    null,
    'users/'.$user->id.'/avatars'
);

// Upload with custom name
$file = $user->uploadFile(
    $request->file('document'),
    'pdf',
    null,
    'documents',
    'custom-filename'
);

// Module-based organization
$file = $user->uploadFileToModule(
    $request->file('profile_picture'),
    'profile',
    'image'
);
```

### 4. Fileable Relationships

[](#4-fileable-relationships)

```
// For Post model with fileable relationship
$file = FileUploader::upload(
    $request->file('image'),
    'image',
    null,
    'posts/'.$postId.'/images',
    'App\Models\Post',
    $postId
);

// Get files for a model
$userFiles = $user->files;
$postImages = $post->files;

// Get files by module
$profileImages = $user->getFilesByModule('profile');
```

### 5. Complete Form Example

[](#5-complete-form-example)

```

    @csrf

             Upload File

             Provide URL

            Any Type
            Image
            Video
            PDF
            Document
            Excel

            Any Type
            Image
            Video
            PDF
            Document
            Excel

    Upload

    document.querySelectorAll('input[name="upload_type"]').forEach(radio => {
        radio.addEventListener('change', function() {
            const isFileUpload = this.value === 'file';
            document.getElementById('file-upload').style.display = isFileUpload ? 'block' : 'none';
            document.getElementById('url-upload').style.display = isFileUpload ? 'none' : 'block';
        });
    });

```

### 6. Controller Implementation

[](#6-controller-implementation)

```
namespace App\Http\Controllers;

use Illuminate\Http\Request;

class FileController extends Controller
{
    public function upload(Request $request)
    {
        $uploadType = $request->input('upload_type', 'file');

        if ($uploadType === 'file') {
            $validated = $request->validate([
                'file' => 'required|file',
                'folder' => 'nullable|string',
                'custom_name' => 'nullable|string',
                'file_type' => 'required|in:any,image,video,pdf,document,excel',
                'max_size' => 'nullable|integer|min:1',
            ]);

            $source = $request->file('file');
            $folder = $request->folder;
            $customName = $request->custom_name;
            $fileType = $request->file_type;
            $maxSize = $request->max_size;
        } else {
            $validated = $request->validate([
                'file_url' => 'required|url',
                'folder' => 'nullable|string',
                'custom_name' => 'nullable|string',
                'file_type' => 'required|in:any,image,video,pdf,document,excel',
                'max_size' => 'nullable|integer|min:1',
            ]);

            $source = $request->input('file_url');
            $folder = $request->folder;
            $customName = $request->custom_name;
            $fileType = $request->file_type;
            $maxSize = $request->max_size;
        }

        try {
            $file = auth()->user()->uploadFile($source, $fileType, $maxSize, $folder, $customName);

            return response()->json([
                'success' => true,
                'file' => [
                    'id' => $file->id,
                    'url' => $file->url,
                    'path' => $file->file_path,
                    'original_name' => $file->original_name,
                    'file_type' => $file->file_type,
                    'size' => $file->file_size,
                ]
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'error' => $e->getMessage()
            ], 400);
        }
    }

    public function delete($fileId)
    {
        $file = \StalkArtisan\LaravelFileUploader\Models\File::findOrFail($fileId);

        // Check ownership or use policies
        if ($file->fileable_id !== auth()->id()) {
            abort(403);
        }

        \StalkArtisan\LaravelFileUploader\Facades\FileUploader::delete($file);

        return response()->json(['success' => true]);
    }
}
```

### 7. Displaying Files

[](#7-displaying-files)

```
{{-- Display user's files --}}
@foreach($user->files as $file)

        @if($file->isImage())

        @elseif($file->isVideo())

        @else

                📄 {{ $file->original_name }}

        @endif

            {{ round($file->file_size / 1024, 2) }} KB •
            {{ $file->created_at->format('M j, Y') }}

            @csrf @method('DELETE')
            Delete

@endforeach
```

API Reference
-------------

[](#api-reference)

### FileUploader Facade Methods

[](#fileuploader-facade-methods)

MethodDescription`upload(UploadedFile $file, string $fileType, ?int $maxSize, ?string $folder, ?string $fileableType, ?int $fileableId)`Upload a file`uploadFromUrl(string $url, string $fileType, ?int $maxSize, ?string $folder, ?string $fileableType, ?int $fileableId)`Upload from URL`handle(mixed $source, string $fileType, ?int $maxSize, ?string $folder, ?string $fileableType, ?int $fileableId)`Handle both file and URL`validateFile(UploadedFile $file, string $fileType, ?int $maxSize)`Validate file`validateUrl(string $url, string $fileType, ?int $maxSize)`Validate URL`delete(File $file)`Delete file`getFileTypeConfig(string $fileType)`Get file type configuration### HasFileUploads Trait Methods

[](#hasfileuploads-trait-methods)

MethodDescription`uploadFile(mixed $source, string $fileType, ?int $maxSize, ?string $folder, ?string $customName)`Upload file for model`uploadFileToModule(mixed $source, string $module, string $fileType, ?int $maxSize, ?string $customName)`Upload to module folder`files()`Get all files for model`getFilesByModule(string $module)`Get files by module`deleteFiles()`Delete all model filesDatabase Schema
---------------

[](#database-schema)

The `files` table includes:

ColumnTypeDescription`id`bigintPrimary key`original_name`stringOriginal file name`file_name`stringStored file name`file_path`stringStorage path`file_size`integerFile size in bytes`mime_type`stringMIME type`extension`stringFile extension`file_type`stringCategory (image, video, pdf, etc.)`source_type`enumSource (upload/url)`source_url`textOriginal URL (for URL downloads)`disk`stringStorage disk`fileable_id`bigintPolymorphic relation ID`fileable_type`stringPolymorphic relation type`created_at`, `updated_at`timestampTimestampsError Handling
--------------

[](#error-handling)

The package throws `InvalidFileException` with specific messages:

- Invalid file provided. - General file validation failure
- Invalid URL: {url} - URL validation failed
- Failed to download file from URL: {url} - URL download failed
- File size exceeds maximum limit of {size} KB - File too large
- Unsupported MIME type: {mime\_type} - Invalid file type

Testing
-------

[](#testing)

Create a test route to verify installation:

```
// routes/web.php
Route::get('/test-upload', function() {
    return view('test-upload-form');
});

Route::post('/test-upload', function(\Illuminate\Http\Request $request) {
    try {
        $file = auth()->user()->uploadFile(
            $request->file('file') ?? $request->input('file_url'),
            $request->file_type ?? 'any',
            $request->max_size,
            $request->folder,
            $request->custom_name
        );

        return back()->with('success', 'File uploaded: ' . $file->url);
    } catch (\Exception $e) {
        return back()->with('error', $e->getMessage());
    }
});
```

Security Features
-----------------

[](#security-features)

- **Path Sanitization**: Prevents directory traversal attacks
- **MIME Type Verification**: Validates file content, not just extension
- **Size Limits**: Configurable maximum file sizes
- **URL Validation**: Ensures only http/https URLs are accepted
- **File Type Restrictions**: Whitelist-based file type validation

Contributing
------------

[](#contributing)

Contributions are welcome! Please:

- Fork the repository
- Create a feature branch
- Make your changes
- Add tests
- Submit a pull request

License
-------

[](#license)

This package is open-sourced software licensed under the [MIT License](LICENSE).

Support
-------

[](#support)

For issues and questions:

- Create an issue on [GitHub](https://github.com/stalkdeveloper/laravel-file-uploader)
- Email:

Happy uploading! 🚀

###  Health Score

32

—

LowBetter than 71% of packages

Maintenance67

Regular maintenance activity

Popularity3

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity44

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 75% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

222d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/e94e2da45aee1b8d5418b2c580fa1a2017931f1a333a5cc230beea97809bfb77?d=identicon)[stalkdeveloper](/maintainers/stalkdeveloper)

---

Top Contributors

[![sunnyhelpful](https://avatars.githubusercontent.com/u/157090514?v=4)](https://github.com/sunnyhelpful "sunnyhelpful (6 commits)")[![stalkdeveloper](https://avatars.githubusercontent.com/u/91655988?v=4)](https://github.com/stalkdeveloper "stalkdeveloper (2 commits)")

---

Tags

artisancomposercomposer-packagefilefile-uploadlaravellaravel-applicationlaravel-frameworkopen-sourcepackagesphpuploader

### Embed Badge

![Health badge](/badges/stalkdeveloper-laravel-file-uploader/health.svg)

```
[![Health](https://phpackages.com/badges/stalkdeveloper-laravel-file-uploader/health.svg)](https://phpackages.com/packages/stalkdeveloper-laravel-file-uploader)
```

###  Alternatives

[yajra/laravel-datatables-oracle

jQuery DataTables API for Laravel

4.9k33.8M335](/packages/yajra-laravel-datatables-oracle)[unisharp/laravel-filemanager

A file upload/editor intended for use with Laravel 5 to 10 and CKEditor / TinyMCE

2.2k3.3M73](/packages/unisharp-laravel-filemanager)[roots/acorn

Framework for Roots WordPress projects built with Laravel components.

9682.1M97](/packages/roots-acorn)[spatie/laravel-google-cloud-storage

Google Cloud Storage filesystem driver for Laravel

2408.9M12](/packages/spatie-laravel-google-cloud-storage)[pressbooks/pressbooks

Pressbooks is an open source book publishing tool built on a WordPress multisite platform. Pressbooks outputs books in multiple formats, including PDF, EPUB, web, and a variety of XML flavours, using a theming/templating system, driven by CSS.

44643.1k1](/packages/pressbooks-pressbooks)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

255.2k](/packages/aedart-athenaeum)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
