Laravel Filemanager

repository·master·Indexed 24 days ago

https://github.com/unisharp/laravel-filemanager

A comprehensive file upload and management solution for Laravel applications. It features a responsive user interface, image cropping, cloud storage integration, and multi-user modes with private and shared folders. The package supports integration with WYSIWYG editors like CKEditor and TinyMCE, provides image optimization and thumbnail generation via intervention/image, and includes a robust event system for customizing file and folder operations.

Tokens
10.2K
Snippets
25
Records
46
Agent score
79%

What's inside laravel-filemanager

  1. Overview of Laravel Filemanager features

    master

    Laravel Filemanager is a comprehensive file management solution for Laravel applications. Key capabilities include:

    • File Management: Uploading, managing, and validating files.
    • Image Processing: Cropping and resizing images.
    • Storage: Integration with cloud storage via the Laravel filesystem.
    • User Interface: Responsive design (RWD) that is fully customizable.
    • Multi-user Modes:
      • Shared folders: A global directory where all users can manage files.
      • Private folders: Dedicated directories per user, restricted to the owner.
    • Integration Options:
      • WYSIWYG editors (CKEditor, TinyMCE, Summernote).
      • Standalone upload buttons.
      • Iframe implementation.
    • Categorization: Separates 'files' and 'images' into different directories.
    • Localization: Supports a wide range of locales including en, es, fr, zh-CN, ar, and many others.
  2. Configure Multi-User Mode (Private and Shared Folders)

    master

    Multi-user mode allows you to separate user files into private folders and provide a shared folder for all users.

    Private Folders

    • allow_private_folder: Enables/disables private folders. Only the owner (the signed-in user) can manage files within their private folder.
    • private_folder_name: The name/prefix for private folders. Defaults to the user ID.

    Shared Folders

    • allow_shared_folder: Enables/disables shared folders. All users can upload and manage files within these folders.
    • shared_folder_name: The name of the shared folder. Defaults to "shares".

    Customizing Folder Logic

    To change how folder names or user fields are determined (e.g., using something other than the user ID), you must implement a custom ConfigHandler:

    1. Run php artisan publish tag="lfm_handler".
    2. Rewrite the userField function in App\Handler\ConfigHandler.
    3. Set the private_folder_name or shared_folder_name config value to App\Handler\ConfigHandler::class.
  3. Upgrade laravel-filemanager via Composer and Artisan

    master

    To upgrade the package, follow these steps to ensure your configuration and assets are correctly updated:

    1. Backup your configuration: Manually back up your existing config/lfm.php file before proceeding.
    2. Update the package: Run composer update unisharp/laravel-filemanager.
    3. Re-publish assets: Use the --force flag to overwrite existing views, public assets, and configuration files with the new versions:
      • Views: php artisan vendor:publish --tag=lfm_view --force
      • Public assets: php artisan vendor:publish --tag=lfm_public --force
      • Configuration: php artisan vendor:publish --tag=lfm_config --force
    4. Clear caches: Clear your application's route and configuration caches:
      • php artisan route:clear
      • php artisan config:clear
    5. Browser Cache: If the UI appears broken after the upgrade, clear your browser cache.
    composer update unisharp/laravel-filemanager
    
    php artisan vendor:publish --tag=lfm_view --force
    php artisan vendor:publish --tag=lfm_public --force
    php artisan vendor:publish --tag=lfm_config --force
    
    php artisan route:clear
    php artisan config:clear
  4. Use Event Subscribers to handle multiple Laravel Filemanager events

    master

    For a cleaner implementation when handling many different events, use an Event Subscriber. Register the subscriber in the $subscribe array of your EventServiceProvider and use the $events->listen('*', ...) pattern to catch all filemanager events in a single class.

    // In EventServiceProvider.php
    protected $subscribe = [
        UploadListener::class
    ];
    
    // The Subscriber implementation
    class UploadListener
    {
        public function subscribe($events)
        {
            $events->listen('*', UploadListener::class);
        }
    
        public function handle($event)
        {
            $method = 'on'.class_basename($event);
            if (method_exists($this, $method)) {
                call_user_func([$this, $method], $event);
            }
        }
    
        public function onImageWasUploaded(ImageWasUploaded $event)
        {
            $path = $event->path();
            // your code
        }
    
        public function onImageWasRenamed(ImageWasRenamed $event)
        {
            // image was renamed
        }
    
        public function onImageWasDeleted(ImageWasDeleted $event)
        {
            // image was deleted
        }
    
        public function onFolderWasRenamed(FolderWasRenamed $event)
        {
            // folder was renamed
        }
    }
  5. Post-installation requirements and checklist

    master

    After running the installation commands, ensure the following steps are completed:

    1. Set APP_URL: Ensure the APP_URL in your .env file is correctly set.
    2. Create Symbolic Link: Run php artisan storage:link to link your storage directory.
    3. Permissions: Ensure the files and images directories (defined in config/lfm.php) are writable by your web server (e.g., using chown or chmod).
    4. Database: Ensure your database exists.
    5. Clear Cache: (Optional) Run php artisan route:clear and php artisan config:clear to refresh your application state.
    6. Verify: Log in to your application and visit /laravel-filemanager/demo to test the installation.
  6. Integrate CKEditor with Laravel Filemanager

    master

    To integrate CKEditor, configure the filebrowser and upload URLs in your CKEditor options. Use the /laravel-filemanager route with the appropriate type parameter (Images or Files). Ensure you include the CSRF token for upload requests.

    Configuration Keys:

    • filebrowserImageBrowseUrl: URL for browsing images.
    • filebrowserImageUploadUrl: URL for uploading images.
    • filebrowserBrowseUrl: URL for browsing files.
    • filebrowserUploadUrl: URL for uploading files.
    <textarea id="my-editor-1" name="content" class="form-control my-editor">{!! old('content', 'test editor content') !!}</textarea>
    <script src="//cdn.ckeditor.com/4.6.2/standard/ckeditor.js"></script>
    <script>
      var options = {
        filebrowserImageBrowseUrl: '/laravel-filemanager?type=Images',
        filebrowserImageUploadUrl: '/laravel-filemanager/upload?type=Images&_token={{csrf_token()}}',
        filebrowserBrowseUrl: '/laravel-filemanager?type=Files',
        filebrowserUploadUrl: '/laravel-filemanager/upload?type=Files&_token={{csrf_token()}}'
      };
    </script>
    
    <script>
    CKEDITOR.replace('my-editor-1', options);
    </script>
  7. Integrate Summernote with Laravel Filemanager

    master

    To use Laravel Filemanager with Summernote, you must define a custom button (e.g., lfm) and add it to the Summernote toolbar. The custom button triggers a function that opens the Filemanager window and uses a callback (window.SetUrl) to receive the selected items and insert them into the editor via context.invoke('insertImage', url).

    // Inside $(document).ready()
    var lfm = function(options, cb) {
      var route_prefix = (options && options.prefix) ? options.prefix : '/laravel-filemanager';
      window.open(route_prefix + '?type=' + options.type || 'file', 'FileManager', 'width=900,height=600');
      window.SetUrl = cb;
    };
    
    var LFMButton = function(context) {
      var ui = $.summernote.ui;
      var button = ui.button({
        contents: '<i class="note-icon-picture"></i> ',
        tooltip: 'Insert image with filemanager',
        click: function() {
          lfm({type: 'image', prefix: '/laravel-filemanager'}, function(lfmItems, path) {
            lfmItems.forEach(function (lfmItem) {
              context.invoke('insertImage', lfmItem.url);
            });
          });
        }
      });
      return button.render();
    };
    
    $('#summernote-editor').summernote({
      toolbar: [['popovers', ['lfm']]],
      buttons: { lfm: LFMButton }
    });
  8. Protect Laravel-Filemanager routes with middleware

    master

    If you define your own routes for Laravel-Filemanager, you must manually apply security middleware to prevent unauthorized file uploads. To restrict access to authenticated users only, wrap the Lfm::routes() call within a Laravel route group using the auth middleware.

    If you are using the default routes provided by the package, ensure that the auth middleware is enabled and correctly configured in config/lfm.php.

    Route::group(['middleware' => 'auth'], function () {
        \UniSharp\LaravelFilemanager\Lfm::routes();
    });
  9. Configure Intervention Image for Laravel

    master

    Laravel Filemanager uses intervention/image for image processing (cropping, resizing, and thumbnails).

    If you are using v3.* or v4.* of intervention/image, you must install the Laravel service provider manually, as these versions do not support Laravel by default.

    Note:

    • Do not run these steps if you are using v2.* of intervention/image.
    • intervention/image v4 requires PHP 8.3 or newer.

    To install the provider:

    composer require intervention/image-laravel
    php artisan vendor:publish --provider="Intervention\Image\Laravel\ServiceProvider"
  10. Customize Laravel Filemanager Routes

    master

    To wrap the package routes with your own prefix and middleware (such as authentication), edit routes/web.php and use a route group. It is highly recommended to include the auth middleware to prevent unauthorized uploads and to ensure multi-user mode functions correctly.

    Route::group(['prefix' => 'laravel-filemanager', 'middleware' => ['web', 'auth']], function () {
        \UniSharp\LaravelFilemanager\Lfm::routes();
    });