Search by

itstructure / laravel-media-file-uploader

itstructure

File manager, album editor and media file uploader for Laravel: local or S3 storage, thumbnails, link files to any model

Package info

github.com/itstructure/laravel-media-file-uploader

pkg:composer/itstructure/laravel-media-file-uploader

Statistics

Installs: 145

Dependents: 0

Suggesters: 0

Stars: 1

Open Issues: 0

1.2.2 2026-12-01 14:23 UTC

This package is auto-updated.

Last update: 2026-12-01 14:24:54 UTC


README

Latest Stable Version Latest Unstable Version License Total Downloads Build Status Scrutinizer Code Quality Tests

1 Introduction

A ready file manager for your Laravel admin panel: upload files, organize them in albums and link them to any model. Images, audio, video, PDF, Office documents and others. Local or Amazon S3 storage.

MFU logotip

What you get: a file manager, an album editor and a FileSetter button to link files with your models (products, pages e.t.c.).

File manager   Album editor

Click a picture to read more.

Why MFU?

  • Ready interface out of the box, for free. A file manager, an upload page, an album editor and a file picker for your forms are already made. You do not need to write the interface yourself.
  • One file, many owners. A file is uploaded once to a common library and can be linked to many models: products, pages, albums. Deleting an owner does not delete files of other owners.
  • Albums. Group images, audio, video and documents in albums and link the albums to your models.
  • Any file types. Images with thumbnails, audio, video, PDF, Office documents, archives and others, with a preview for each type.
  • Local or Amazon S3 storage by a simple config option.
  • Bootstrap 4 or 5, jQuery is not needed. It fits a modern admin panel and an old one (for example AdminLTE 3).

Compared with spatie/laravel-medialibrary: it is a great library to attach files to a model in code, but it has no free interface, and a file belongs to one model. MFU is for the case, when you need a ready file manager in your admin panel and a common file library for the whole site.

Quick start in 5 minutes

A short way to see the file manager working. Details of each step are in the sections below.

  1. Install the package (more: 3.1):

    composer require itstructure/laravel-media-file-uploader "^1.2.2"

  2. Publish config, migrations, assets, views and translations (more: 3.3 - 3.5):

    php artisan uploader:publish

  3. Create the tables (more: 3.6):

    php artisan migrate

  4. Set a disk for files in config/filesystems.php and create a link to it (more: 4.1):

    php artisan storage:link

  5. Open the file manager in a browser and upload a first file (more: 5.2.1):

    http://example-domain.com/uploader/managers/file-list

Before production protect the routes and allowed file types: see 4.4 Security.

Next steps:

  • Choose files in your forms with FileSetter: 5.3.3.
  • Link files and albums with your models: 5.3.4.
  • Album editor: 5.2.6.

2 Requirements

  • laravel 8.37+ | 9+ | 10+ | 11+ | 12+ | 13+
  • Bootstrap 4 or 5 for styling
  • php >= 7.3
  • composer 2
  • One of the next php extensions: GD|Imagick|Gmagick
  • Database: MySQL, MariaDB, PostgreSQL or SQLite

The imagine/imagine library (for thumbnails) is installed automatically with the package since version 1.1.0.

jQuery is not needed since version 1.2.0.

Note! Versions 1.0.x declared Laravel 6 and 7 too, but the migrations and uploading did not work there. Since version 1.1.0 the minimal Laravel version is 8.37.

3 Installation

3.1 Install package

General from remote Packagist repository

Run the composer command:

composer require itstructure/laravel-media-file-uploader "^1.2.2"

If you are testing this package from a local server directory

In application composer.json file set the repository, as in example:

"repositories": [
    {
        "type": "path",
        "url": "../laravel-media-file-uploader",
        "options": {
            "symlink": true
        }
    }
],

Here,

../laravel-media-file-uploader - directory path, which has the same directory level as application and contains MFU package.

Then run command:

composer require itstructure/laravel-media-file-uploader:dev-main --prefer-source

3.3 Publish files - Required part

  • To publish config run command:

    php artisan uploader:publish --only=config

    It stores config file to config folder.

    Else you can use --force argument to rewrite already published file.

  • To publish migrations run command:

    php artisan uploader:publish --only=migrations

    It stores migration files to database/migrations folder.

    Else you can use --force argument to rewrite already published files.

  • To publish assets (js and css) run command:

    php artisan uploader:publish --only=assets

    It stores js and css files to public/vendor/uploader folder.

    Else you can use --force argument to rewrite already published files.

3.4 Publish files - Custom part

  • To publish views run command:

    php artisan uploader:publish --only=views

    It stores view files to resources/views/vendor/uploader folder.

    Else you can use --force argument to rewrite already published file.

  • To publish translations run command:

    php artisan uploader:publish --only=lang

    It stores translation files to resources/lang/vendor/uploader folder.

    Else you can use --force argument to rewrite already published file.

3.5 Publish files - All parts if needed

  • To publish all parts run command without only argument:

    php artisan uploader:publish

    Else you can use --force argument to rewrite already published files.

3.6 Run migrations

  • Run command:

php artisan migrate

4 Configure

4.1 Set default filesystem disk

In a config file filesystems.php set the next custom settings (set default disk which you wish) and create needed base upload folder:

'default' => env('FILESYSTEM_DISK', 'local'),

'disks' => [
    'local' => [
        'driver' => 'local',
        'root' => storage_path('app/uploads'),
        'throw' => false,
        'url' => env('APP_URL') . '/storage/',
        'visibility' => 'public',
    ],
    's3' => [
        'driver' => 's3',
        'key' => env('AWS_ACCESS_KEY_ID'),
        'secret' => env('AWS_SECRET_ACCESS_KEY'),
        'region' => env('AWS_DEFAULT_REGION'),
        'bucket' => env('AWS_BUCKET'),
        'url' => env('AWS_URL'),
        'endpoint' => env('AWS_ENDPOINT'),
        'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false),
        'throw' => false,
        'visibility' => 'public',
    ],
],

'links' => [
    public_path('storage') => storage_path('app/uploads'),
],

Run command to create symbolic links:

php artisan storage:link

Important! Do not forget 'visibility' => 'public' for the local disk. Without it Laravel creates the upload folders with 700 permissions: only the PHP user can open them. If your web server (for example nginx) works under another user (often in Docker), the files are not shown: the browser gets an error 403.

If the folders are already created without this option, add the option and fix the permissions of the existing folders:

find storage/app/uploads -type d -exec chmod 755 {} +

4.2 Set assets

Pay Attention! This option is needed just in the next cases:

  • If you use a File setter in your app html forms (see 5.3 Digging deeper / 5.3.3 Use FileSetter point).

  • If you use an Album editor (see in 5.1 Routes part).

Make sure you use Bootstrap 4 or Bootstrap 5 for styling in your application.

The modal window of the file manager is opened by Bootstrap JavaScript, which is on your page: Bootstrap 5 (bootstrap.bundle.js) or Bootstrap 4 with jQuery. If there is no Bootstrap JavaScript on the page, the package opens a simple modal window itself.

4.2.1 Custom body layout case

So, set the next css assets between head tags of your app layout:

<link rel="stylesheet" href="{{ asset('vendor/uploader/css/modal.css') }}">
<link rel="stylesheet" href="{{ asset('vendor/uploader/css/file-area.css') }}">

Set the next js asset at the end of the body tag of your app layout:

<script src="{{ asset('vendor/uploader/js/file-setter.js') }}"></script>

jQuery is not needed since version 1.2.0. The file vendor/uploader/js/jquery.min.js is still in the package only for old layouts, which include it.

Updating from version 1.1.x or older? Publish the assets again, to get the new scripts and styles:

php artisan uploader:publish --only=assets --force

If you published the views, publish them again too: php artisan uploader:publish --only=views --force.

4.2.2 If you use AdminLTE package in your project

'plugins' => [
    'Uploader' => [
        'active' => true,
        'files' => [
            [
                'type' => 'css',
                'asset' => true,
                'location' => '/vendor/uploader/css/modal.css',
            ],
            [
                'type' => 'css',
                'asset' => true,
                'location' => '/vendor/uploader/css/file-area.css',
            ],
            [
                'type' => 'js',
                'asset' => true,
                'location' => '/vendor/uploader/js/file-setter.js',
            ],
        ],
    ],
]

Pay attention: Not recommended using of asset() in AdminLTE config file, because it may cause an error with UrlGenerator.php when you will run fore example composer install later.

4.3 Change uploader.php config file.

This file is intuitive.

But at this stage, pay attention to the next important options:

  • Routing middlewares. By default it is empty array, you can set for example like this:

    'routing' => [
        'middlewares' => ['auth'],
    ],

    This middlewares will be applied in the routes/uploader.php.

    Important! Read the next point 4.4 about security.

  • Albums layout (Needed if you use Album editor). By default it is empty string, you can set for example like this:

    'albums' => [
        'layout' => 'adminlte::page', // In case if you use AdminLTE. Or you can set your special layout.
    ],

4.4 Security: protect the routes and the file types

By default the package gives you full freedom: the routes are not protected and any file type can be uploaded. It is made on purpose, so that you can set the protection, which fits your application. But you must set it before using the package in production.

What is open by default:

  • 'routing' => ['middlewares' => []] - anybody, even a not logged in visitor, can upload, update, delete and download files, and manage albums.
  • 'checkExtensionByFileType' => false - any file type can be uploaded, only the file size is checked. For example .php, .html or .svg files.

Why it is dangerous: uploaded files are saved to a public disk. If anybody can upload a .php file and your web server executes php files in the public folder, it is an execution of a foreign code on your server. An .html or .svg file with JavaScript can steal sessions of your users.

How to protect, step by step:

  1. Set middlewares for the routes. For example, only logged in users:

    'routing' => [
        'middlewares' => ['auth'],
    ],

    Or only users with a special permission (for example with itstructure/laravel-rbac):

    'routing' => [
        'middlewares' => ['auth', 'can:administrate'],
    ],
  2. Allow only needed file types:

    'checkExtensionByFileType' => true,

    Then the extensions from fileExtensions option are checked for each file type. Check this list and remove what you do not need (for example exe).

  3. Make sure, your web server does not execute php files in the upload folder (for example storage/app/public and public/storage). In a standard Laravel setup only public/index.php must be executed.

Also good to know:

  • The sub_dir field of an upload request is used as a part of the file path. Since version 1.1.0 only normal folder names are used from it: .., . and empty parts are removed. For example /products/2024/ gives products/2024, and ../../secret gives secret.
  • Since version 1.1.0 an error 400 shows an error text only if APP_DEBUG=true. Else the text is Bad request., and the error is written to the log.

5 Usage

5.1 Routes part

There are already integrated base MFU routes to manage files and albums. See in routes/uploader.php package file.

The next routes are available by default:

  • Uploading section

    For GET request method

    • http://example-domain.com/uploader/file/download/{id} (Name: uploader_file_download)

    For POST request method

    • http://example-domain.com/uploader/file/upload (Name: uploader_file_upload)

      • Required request field is file.
      • Optional/required request meta data fields: [data]alt, [data]title, [data]description, [data]owner_id, [data]owner_name, [data]owner_attribute, [data]needed_file_type, [data]sub_dir.
    • http://example-domain.com/uploader/file/update (Name: uploader_file_update)

      • Required request field is id.
      • Optional request field is file.
      • Optional/required request meta data fields: [data]alt, [data]title, [data]description, [data]needed_file_type, [data]sub_dir.
    • http://example-domain.com/uploader/file/delete (Name: uploader_file_delete)

      • Required request field is id.
    • http://example-domain.com/uploader/file/preview (Name: uploader_file_preview)

      • Required request field is id.
      • Optional request field is location. See more for preview option in config uploader.php (there are some html attributes for concrete file types and their previews). If not set, returned preview will be with html attributes according with Previewer::LOCATION_FILE_INFO. Also if it is an image, Previewer will return an image with sizes, according with thumbAlias option in config. If thumbAlias is not set or there is no such location, Previewer will return image with sizes according with SaveProcessor::THUMB_ALIAS_SMALL.

    Notes:

    • If uploading file is an image, then additional thumbnails will be created according with their settings in thumbSizes config option.
    • Requirement/optionality for request meta data fields is set in metaDataValidationRules option of config uploader.php file.
    • If checkExtensionByFileType option is true, then [data]needed_file_type is required automatically.
  • Managing section

    For GET request method

    • http://example-domain.com/uploader/managers/file-list (Name: uploader_file_list_manager)
    • http://example-domain.com/uploader/managers/file-upload (Name: uploader_file_upload_manager)
    • http://example-domain.com/uploader/managers/file-edit/{id} (Name: uploader_file_edit_manager)

    For POST request method

    • http://example-domain.com/uploader/managers/file-list/delete (Name: uploader_file_list_delete)
      • Required request field is items - it is an array of file's ID's.
  • Album editor section

    • Image albums

      For GET request method

      • http://example-domain.com/uploader/albums/image/list (Name: uploader_image_album_list)
      • http://example-domain.com/uploader/albums/image/create (Name: uploader_image_album_create)
      • http://example-domain.com/uploader/albums/image/edit/{id} (Name: uploader_image_album_edit)
      • http://example-domain.com/uploader/albums/image/view/{id} (Name: uploader_image_album_view)

      For POST request method

      • http://example-domain.com/uploader/albums/image/store (Name: uploader_image_album_store)
      • http://example-domain.com/uploader/albums/image/update/{id} (Name: uploader_image_album_update)
      • http://example-domain.com/uploader/albums/image/delete (Name: uploader_image_album_delete)
    • Audio albums

      For GET request method

      • http://example-domain.com/uploader/albums/audio/list (Name: uploader_audio_album_list)
      • http://example-domain.com/uploader/albums/audio/create (Name: uploader_audio_album_create)
      • http://example-domain.com/uploader/albums/audio/edit/{id} (Name: uploader_audio_album_edit)
      • http://example-domain.com/uploader/albums/audio/view/{id} (Name: uploader_audio_album_view)

      For POST request method

      • http://example-domain.com/uploader/albums/audio/store (Name: uploader_audio_album_store)
      • http://example-domain.com/uploader/albums/audio/update/{id} (Name: uploader_audio_album_update)
      • http://example-domain.com/uploader/albums/audio/delete (Name: uploader_audio_album_delete)
    • Video albums

      For GET request method

      • http://example-domain.com/uploader/albums/video/list (Name: uploader_video_album_list)
      • http://example-domain.com/uploader/albums/video/create (Name: uploader_video_album_create)
      • http://example-domain.com/uploader/albums/video/edit/{id} (Name: uploader_video_album_edit)
      • http://example-domain.com/uploader/albums/video/view/{id} (Name: uploader_video_album_view)

      For POST request method

      • http://example-domain.com/uploader/albums/video/store (Name: uploader_video_album_store)
      • http://example-domain.com/uploader/albums/video/update/{id} (Name: uploader_video_album_update)
      • http://example-domain.com/uploader/albums/video/delete (Name: uploader_video_album_delete)
    • Application albums

      For GET request method

      • http://example-domain.com/uploader/albums/application/list (Name: uploader_application_album_list)
      • http://example-domain.com/uploader/albums/application/create (Name: uploader_application_album_create)
      • http://example-domain.com/uploader/albums/application/edit/{id} (Name: uploader_application_album_edit)
      • http://example-domain.com/uploader/albums/application/view/{id} (Name: uploader_application_album_view)

      For POST request method

      • http://example-domain.com/uploader/albums/application/store (Name: uploader_application_album_store)
      • http://example-domain.com/uploader/albums/application/update/{id} (Name: uploader_application_album_update)
      • http://example-domain.com/uploader/albums/application/delete (Name: uploader_application_album_delete)
    • Word albums

      For GET request method

      • http://example-domain.com/uploader/albums/word/list (Name: uploader_word_album_list)
      • http://example-domain.com/uploader/albums/word/create (Name: uploader_word_album_create)
      • http://example-domain.com/uploader/albums/word/edit/{id} (Name: uploader_word_album_edit)
      • http://example-domain.com/uploader/albums/word/view/{id} (Name: uploader_word_album_view)

      For POST request method

      • http://example-domain.com/uploader/albums/word/store (Name: uploader_word_album_store)

      • http://example-domain.com/uploader/albums/word/update/{id} (Name: uploader_word_album_update)

      • http://example-domain.com/uploader/albums/word/delete (Name: uploader_word_album_delete)

        .........................................................

        ................Next albums...............

        .........................................................

E.t.c... See in routes/uploader.php package file the next albums routes for Excel, Visio, PowerPoint, PDF, Text, Other albums. They have similar principle.

Album editor POST request method fields are equal for all albums:

  • Required request fields for store: title, description.
  • Required request fields for update: title, description. Field id is in route url.
  • Required request field for delete: items - it is an array of album's ID's.

5.2 Easy quick way

5.2.1 Access to File list manager

  • Go directly to uploader_file_list_manager route: http://example-domain.com/uploader/managers/file-list

  • Go to File list using iframe:

<section class="content container-fluid">
    <div class="row">
        <div class="col-12 mt-1">
            <iframe src="{{ route('uploader_file_list_manager') }}" frameborder="0" style="width: 100%; min-height: 800px"></iframe>
        </div>
    </div>
</section>

MFU file list manager

5.2.2 Access to File upload manager

If to click on green Uploader button in a file list manager, you will go to uploader_file_upload_manager route: http://example-domain.com/uploader/managers/file-upload.

MFU file upload manager

5.2.3 Access to File edit manager

If to click on green edition button in a file list manager, you will go to uploader_file_edit_manager route: http://example-domain.com/uploader/managers/file-edit/{id}:

route('uploader_file_edit_manager', ['id' => 1])

MFU file edit manager

5.2.4 Access to Media file preview

If you have got a media file entry $mediaFile by Itstructure\MFU\Models\Mediafile model entity:

<a href="{{ $mediaFile->getOriginalUrl() }}" target="_blank">
    {!! \Itstructure\MFU\Facades\Previewer::getPreviewHtml($mediaFile, \Itstructure\MFU\Services\Previewer::LOCATION_FILE_INFO) !!}
</a>

Here you can use some of the next options:

\Itstructure\MFU\Services\Previewer::LOCATION_FILE_ITEM \Itstructure\MFU\Services\Previewer::LOCATION_FILE_INFO \Itstructure\MFU\Services\Previewer::LOCATION_EXISTING

5.2.5 Download Media file

Use route:

route('uploader_file_download', ['id' => 1])

5.2.6 Access to Album Editor

Simply use albums routes, described above in Album editor section of 5.1 Routes part.

But pay attention! You must set a layout for album editor:

'albums' => [
    'layout' => 'adminlte::page',
],

Value adminlte::page is for case if you use AdminLTE. Or you can set your special layout.

Image album list example looks like this:

MFU album list

Image album edition page example looks like this:

MFU album edit

5.3 Digging deeper

5.3.1 Data base structure

MFU db

5.3.2 Short architecture structure and request way for uploading process in simple words

  1. Call UploadController method.

  2. Call static method from Itstructure\MFU\Facades\Uploader facade in controller method.

  3. Get instance of Uploader service Itstructure\MFU\Services\Uploader::getInstance($config) and call here a facade's method.

  4. Get instance of needed processor, with set config data from service to this:

    Itstructure\MFU\Processors\UploadProcessor or

    Itstructure\MFU\Processors\UpdateProcessor or

    Itstructure\MFU\Processors\DeleteProcessor.

  5. Set process parameters and then call it's run() method.

See inside core.

5.3.3 Use FileSetter

FileSetter is needed to set file id in to the form field and file preview to special container before sending request to controller during saving some entity: Page, Catalog, Product e.t.c.

Example FileSetter using for thumbnail:

@php
    $thumbModel = isset($model) ? $model->getThumbnailModel() : null;
@endphp
<div id="{{ isset($model) ? 'thumbnail_container_' . $model->id : 'thumbnail_container' }}">
    @if(!empty($thumbModel))
        <a href="{{ $thumbModel->getOriginalUrl() }}" target="_blank">
            {!! \Itstructure\MFU\Facades\Previewer::getPreviewHtml($thumbModel, \Itstructure\MFU\Services\Previewer::LOCATION_FILE_INFO) !!}
        </a>
    @endif
</div>
<div id="{{ isset($model) ? 'thumbnail_title_' . $model->id : 'thumbnail_title' }}">
    @if(!empty($thumbModel))
        {{ $thumbModel->title }}
    @endif
</div>
<div id="{{ isset($model) ? 'thumbnail_description_' . $model->id : 'thumbnail_description' }}">
    @if(!empty($thumbModel))
        {{ $thumbModel->description }}
    @endif
</div>
@php
    $fileSetterConfig = [
        'attribute' => Itstructure\MFU\Processors\SaveProcessor::FILE_TYPE_THUMB,
        'value' => !empty($thumbModel) ? $thumbModel->id : null,
        'openButtonName' => trans('uploader::main.set_thumbnail'),
        'clearButtonName' => trans('uploader::main.clear'),
        'mediafileContainerId' => isset($model) ? 'thumbnail_container_' . $model->id : 'thumbnail_container',
        'titleContainerId' => isset($model) ? 'thumbnail_title_' . $model->id : 'thumbnail_title',
        'descriptionContainerId' => isset($model) ? 'thumbnail_description_' . $model->id : 'thumbnail_description',
        //'callbackBeforeInsert' => 'function (e, v) {console.log(e, v);}',//Custom
        'neededFileType' => Itstructure\MFU\Processors\SaveProcessor::FILE_TYPE_THUMB,
        'subDir' => isset($model) ? $model->getTable() : null
    ];

    $ownerConfig = isset($ownerParams) && is_array($ownerParams) ? array_merge([
        'ownerAttribute' => Itstructure\MFU\Processors\SaveProcessor::FILE_TYPE_THUMB
    ], $ownerParams) : [];

    $fileSetterConfig = array_merge($fileSetterConfig, $ownerConfig);
@endphp
@fileSetter($fileSetterConfig)

The callbackBeforeInsert option is a JavaScript function, which is called before a chosen file is inserted. It gets an event and an ID of the file: function (e, fileId) {...}. It works with jQuery and without it.

Visually it looks like that:

MFU file setter

If to click on Set thumbnail button, then file list manager will be opened, but with additional button "V":

MFU file list with file setter button

This button is to choose a concrete file and insert it's preview in to the thumbnail_container and it's ID in to the automatically rendered form field by attribute option.

See next point 5.3.4 to understand how this selected file can be linked with a parent owner, like for example: Page, Product e.t.c...

5.3.4 Link media files with parent owner

For example you use Product eloquent model, which contains albums and media files both.

Albums and media files can be linked with Product, after Product is saved, through owners_albums and owners_mediafiles DB relations.

This relations are set by BehaviorMediafile and BehaviorAlbum classes automatically.

namespace App\Models;
    
use Illuminate\Database\Eloquent\Model;
use Itstructure\MFU\Interfaces\BeingOwnerInterface;
use Itstructure\MFU\Behaviors\Owner\{BehaviorMediafile, BehaviorAlbum};
use Itstructure\MFU\Processors\SaveProcessor;
use Itstructure\MFU\Models\Albums\AlbumTyped;
use Itstructure\MFU\Traits\{OwnerBehavior, Thumbnailable};
    
class Product extends Model implements BeingOwnerInterface
{
    use Thumbnailable, OwnerBehavior;
    
    protected $table = 'products';
    
    protected $fillable = ['title', 'alias', 'description', 'price', 'category_id'];
    
    public function getItsName(): string
    {
        return $this->getTable();
    }
    
    public function getPrimaryKey()
    {
        return $this->getKey();
    }
    
    public static function getBehaviorMadiafileAttributes(): array
    {
        return [SaveProcessor::FILE_TYPE_THUMB, SaveProcessor::FILE_TYPE_IMAGE];
    }
    
    public static function getBehaviorAlbumAttributes(): array
    {
        return [AlbumTyped::ALBUM_TYPE_IMAGE];
    }
    
    public static function getBehaviorAttributes(): array
    {
        return array_merge(static::getBehaviorMadiafileAttributes(), static::getBehaviorAlbumAttributes());
    }
    
    protected static function booted(): void
    {
        $behaviorMediafile = BehaviorMediafile::getInstance(static::getBehaviorMadiafileAttributes());
        $behaviorAlbum = BehaviorAlbum::getInstance(static::getBehaviorAlbumAttributes());
    
        static::saved(function (Model $ownerModel) use ($behaviorMediafile, $behaviorAlbum) {
            if ($ownerModel->wasRecentlyCreated) {
                $behaviorMediafile->link($ownerModel);
                $behaviorAlbum->link($ownerModel);
            } else {
                $behaviorMediafile->refresh($ownerModel);
                $behaviorAlbum->refresh($ownerModel);
            }
        });
    
        static::deleted(function (Model $ownerModel) use ($behaviorMediafile, $behaviorAlbum) {
            $behaviorMediafile->clear($ownerModel);
            $behaviorAlbum->clear($ownerModel);
        });
    }
}

The main rules:

  • It is very important to be implemented from BeingOwnerInterface!

  • It is very important to use OwnerBehavior trait. Some required BASE methods by BeingOwnerInterface are already existing in this trait.

  • It is very important to make the next methods: getItsName(), getPrimaryKey().

  • It is very important to add method booted() with behaviour instances.

  • It is very important to set getBehaviorAttributes() with attributes list, which are used in a blade form for FileSetter!

  • Links are updated only for the attributes, which are passed at saving. A form with FileSetter always passes them. But if you save a model from code without these attributes (for example $product->update(['price' => 500])), its links stay as they were. Before version 1.1.0 such saving removed all links of the model.

See deeper in to core and imagine how it works :-)

Go next...

It is very important to use MFU blade partials correctly in your application blade forms!

Short cut example for the blade form with using

uploader::partials.thumbnail,

uploader::partials.new-mediafiles,

uploader::partials.existing-mediafiles,

uploader::partials.albums-form-list:

<form action="{{ route('admin_product_store') }}" method="post">

<div class="row">
    <div class="col-12 col-sm-10 col-md-8 col-lg-6 col-xl-4">
        @include('uploader::partials.thumbnail', ['model' => $model ?? null, 'ownerParams' => $ownerParams ?? null])
    </div>
</div>

<div class="row">
    <div class="col-12 col-sm-10 col-md-8 col-lg-6 col-xl-4">
        <div class="form-group">
            <label for="id_title">Title</label>
            <input id="id_title" type="text" class="form-control @if ($errors->has('title')) is-invalid @endif"
                   name="title" value="{{ old('title', !empty($model) ? $model->title : null) }}" required autofocus>
            @if ($errors->has('title'))
                <div class="invalid-feedback">
                    <strong>{{ $errors->first('title') }}</strong>
                </div>
            @endif
        </div>
    </div>
</div>

..........

..........

<hr />
<h5>{{ trans('uploader::main.new_files') }}</h5>
<div class="row mb-3">
    @include('uploader::partials.new-mediafiles', [
        'fileType' => \Itstructure\MFU\Processors\SaveProcessor::FILE_TYPE_IMAGE,
        'ownerParams' => $ownerParams ?? null
    ])
</div>

@if(!empty($edition))
    <hr />
    <h5>{{ trans('uploader::main.existing_files') }}</h5>
    <div class="row mb-3">
        @include('uploader::partials.existing-mediafiles', [
            'edition' => true,
            'fileType' => \Itstructure\MFU\Processors\SaveProcessor::FILE_TYPE_IMAGE,
            'ownerParams' => $ownerParams ?? null,
            'mediaFiles' => $mediaFiles ?? []
        ])
    </div>
@endif

@if(!empty($allImageAlbums) && !$allImageAlbums->isEmpty())
    <hr />
    <h5>{{ trans('uploader::main.image_albums') }}</h5>
    <div class="row mb-3">
        @include('uploader::partials.albums-form-list', [
            'albums' => $allImageAlbums,
            'edition' => true
        ])
    </div>
@endif

<button class="btn btn-primary" type="submit">Create</button>
<input type="hidden" value="{!! csrf_token() !!}" name="_token">

</form>

To clarify:

By fileType there will be set a field image[], which will be set by fill() method in Itstructure\MFU\Traits\OwnerBehavior trait using getBehaviorAttributes(), and then it's value will be put in to the BehaviorMediafile object during booted() calling after for example Product is saved. Then a table owners_mediafiles will be filled. Link between Product and Mediafile will be created.

Product edition page example looks like this:

MFU product edit

To see more, how that example works in global, see real example here: Laravel Microshop.

I hope you will be happy with this package. Good luck with your development!

6 Tests

The package has its own tests. They check uploading, updating and deleting of files, thumbnails, linking files and albums with owner models, file manager and album pages.

Good to know before you start:

  • By default the tests do not need a database server and do not need a .env file. They use SQLite in memory, everything is created and deleted automatically.
  • The tests work on all supported versions: PHP 7.3 ... 8.5 and Laravel 8.37 ... 13.
  • When you install dependencies of the package, the vendor folder and the composer.lock file appear in the package folder. It is normal. They are in .gitignore, so they will not get into git.

Below there are several ways to run the tests. Choose the one, which fits you.

6.1 Way 1. You have PHP and Composer on your computer

  1. Get the package source code.

    If you have git, run command:

    git clone https://github.com/itstructure/laravel-media-file-uploader.git

    If you do not have git, open https://github.com/itstructure/laravel-media-file-uploader, press the green Code button, then Download ZIP, and unpack the archive.

  2. Go to the package folder:

    cd laravel-media-file-uploader

  3. Install dependencies (it is enough to do it once):

    composer install

    Composer itself chooses the Laravel and PHPUnit versions, which fit your PHP version.

    Note! PHP must have pdo_sqlite, mbstring and fileinfo extensions. Usually they are already enabled. The gd extension is needed for the thumbnail test: without it this test is skipped.

  4. Run the tests:

    composer test

    Or the same directly:

    • Linux / macOS: vendor/bin/phpunit
    • Windows: vendor\bin\phpunit
  5. If you want to run only one test, add --filter with the test name:

    vendor/bin/phpunit --filter test_upload_text_file

If everything is fine, you will see a message like: OK (20 tests, 96 assertions). If PHP has no gd extension, the thumbnail test is skipped, then the message is OK, but some tests were skipped!.

6.2 Way 2. You have nothing except Docker

You do not need to install PHP and Composer. Docker downloads them by itself.

  1. Get the package source code and go to the package folder, as in steps 1 and 2 of Way 1.

  2. Install dependencies (it is enough to do it once).

    For Linux, macOS and WSL terminal:

    docker run --rm --user "$(id -u):$(id -g)" -e COMPOSER_HOME=/tmp/composer -v "$PWD":/app -w /app composer:2 composer update --no-interaction

    For Windows PowerShell:

    docker run --rm -v "${PWD}:/app" -w /app composer:2 composer update --no-interaction

    Here:

    • --user "$(id -u):$(id -g)" - files in the vendor folder will belong to you, not to the root user. In Windows PowerShell it is not needed.
    • -v "$PWD":/app - the current folder (package folder) is available inside the container as /app.
  3. Run the tests.

    For Linux, macOS and WSL terminal:

    docker run --rm --user "$(id -u):$(id -g)" -v "$PWD":/app -w /app php:8.4-cli php vendor/bin/phpunit

    For Windows PowerShell:

    docker run --rm -v "${PWD}:/app" -w /app php:8.4-cli php vendor/bin/phpunit

    To run only one test, add --filter test_name to the end of the command.

Note! In step 2 Composer installs the newest versions of Laravel and PHPUnit. They need a new PHP, so in step 3 use php:8.4-cli or newer. To check an old PHP or Laravel version, see Way 3.

6.3 Way 3. Check a specific PHP and Laravel version with Docker

It is useful, when you want to make sure that the package works for example on PHP 7.3 with Laravel 8.

  1. Choose a pair of versions from the table:

    PHP image Laravel Testbench
    php:7.3-cli 8.* 6.*
    php:8.0-cli 9.* 7.*
    php:8.1-cli 10.* 8.*
    php:8.2-cli 11.* 9.*
    php:8.3-cli 12.* 10.*
    php:8.3-cli 13.* 11.*

    Testbench (orchestra/testbench) is a tool for testing Laravel packages. Each Laravel version needs its own Testbench version, that is why it is in the table.

  2. Go to the package folder. If you have already installed dependencies before, delete the vendor folder and the composer.lock file.

  3. Install dependencies for the chosen pair. Example for PHP 7.3 + Laravel 8 (Linux, macOS, WSL terminal):

    docker run --rm --user "$(id -u):$(id -g)" -e COMPOSER_HOME=/tmp/composer -v "$PWD":/app -w /app composer:2 sh -c "composer config platform.php 7.3.33 && composer config policy.advisories.block false && composer require --no-update 'laravel/framework:8.*' && composer require --dev --no-update 'orchestra/testbench:6.*' && composer update --no-interaction --no-plugins"

    What this command does:

    • composer config platform.php 7.3.33 - tells Composer to choose packages for PHP 7.3, because Composer itself works on a newer PHP inside its container.
    • composer config policy.advisories.block false - allows installing old Laravel versions. New Composer refuses to install versions with known security advisories. It is OK for running tests, but never do it in a real project.
    • composer require --no-update ... - sets the chosen Laravel and Testbench versions.
    • --no-plugins - old Laravel versions bring Composer plugins, which are not needed for tests and are blocked by new Composer.

    For another pair, change 7.3.33, 8.* and 6.* to the values from the table. For platform.php you can write any version of the chosen PHP, for example 8.0.30, 8.2.0.

  4. Run the tests with the PHP image from the table:

    docker run --rm --user "$(id -u):$(id -g)" -v "$PWD":/app -w /app php:7.3-cli php vendor/bin/phpunit
  5. Important! The command in step 3 changes the composer.json file of the package. When you finish, return it back and delete the installed files:

    git checkout composer.json

    And delete the vendor folder and the composer.lock file.

    If you downloaded the package as ZIP (without git), just download and unpack it again.

6.4 Way 4. Run the tests on PostgreSQL or MySQL

By default the tests use SQLite. But the package migrations work a little differently on different databases (for example a json column in MySQL). So it is useful to check a real database server too.

Set environment variables before running the tests:

Variable Value
UPLOADER_TEST_DB pgsql or mysql
UPLOADER_TEST_DB_HOST server host, by default 127.0.0.1
UPLOADER_TEST_DB_PORT by default 5432 for pgsql, 3306 for mysql
UPLOADER_TEST_DB_DATABASE by default uploader_test
UPLOADER_TEST_DB_USERNAME by default root
UPLOADER_TEST_DB_PASSWORD by default empty

Important! Use an empty database only for tests. Before each test all tables in it are deleted.

Example with a temporary PostgreSQL in Docker (Linux, macOS, WSL terminal):

  1. Start a temporary PostgreSQL server:

    docker run -d --rm --name uploader-test-pg -p 127.0.0.1:55432:5432 -e POSTGRES_PASSWORD=secret -e POSTGRES_DB=uploader_test postgres:17
  2. Run the tests (PHP must have pdo_pgsql extension):

    UPLOADER_TEST_DB=pgsql UPLOADER_TEST_DB_PORT=55432 UPLOADER_TEST_DB_USERNAME=postgres UPLOADER_TEST_DB_PASSWORD=secret vendor/bin/phpunit
  3. Stop the server (it is deleted automatically, because of --rm):

    docker stop uploader-test-pg

6.5 Way 5. Automatic tests on GitHub

You do not need to do anything. After each push and each pull request, GitHub runs the tests by itself on all version pairs from the table above (and a few more), and also on PostgreSQL and MySQL.

Results are on the Actions tab of the repository: https://github.com/itstructure/laravel-media-file-uploader/actions

Green check mark - all tests passed. Red cross - something is broken, open it to see the details.

The settings are in the .github/workflows/tests.yml file.

6.6 If the package is installed in your Laravel project

  1. Your project tests and the package tests do not mix.

    When you run tests of your project (composer test, php artisan test or vendor/bin/phpunit in the project folder), only tests of your project are run. The project phpunit.xml file points to the project tests folder, and the package lies in vendor/itstructure/laravel-media-file-uploader. So the package tests are not run there.

  2. Usually there are no package tests in your project at all.

    By default Composer downloads the package as an archive. The tests folder, the .github folder and the phpunit.xml.dist file are excluded from this archive (see the .gitattributes file), because they are not needed for the package to work. So in vendor/itstructure/laravel-media-file-uploader there is only the package itself.

  3. Exception: installation with --prefer-source or from a local folder.

    If the package is installed with --prefer-source (Composer makes git clone instead of downloading an archive), or from a local folder ("type": "path" repository), then the whole repository is in the project, the tests too.

    It does not break anything: your project tests still do not run them.

  4. How to run the package tests in this case.

    Do not run them through your project, the project has no tools needed for the package tests.

    Run them in the package folder itself, as described in Way 1 or Way 2:

    • If the package is installed from a local folder ("type": "path"), go to that local folder.
    • Otherwise, just clone the package repository to a separate folder.

With all respect, Andrey!

License

Copyright © 2024-2026 Andrey Girnik girnikandrey@gmail.com.

Licensed under the MIT license. See LICENSE.txt for details.