Multiple File upload in laravel7

Hi friends, in this blog i’ll try to explain you multiple server side file upload in laravel 7 with example for beginners.

  • All videos will be converted to mp4.
  • All audio will be converted to mp3.
  • All images width & height & ratio will be saved as a custom property.
  • All videos & audio’s duration will be saved as a custom property.

Installation

composer require ahmed-aliraqi/laravel-media-uploader

The package will automatically register a service provider.

You need to publish and run the migration:

php artisan vendor:publish --provider="AhmedAliraqi\LaravelMediaUploader\Providers\UploaderServiceProvider" --tag="migrations"

php artisan migrate

Publish laravel-media-library migrations:

php artisan vendor:publish --provider="Spatie\MediaLibrary\MediaLibraryServiceProvider" --tag="migrations"
php artisan migrate

If you want to customize attachments validation rules, you should publish the config file:

php artisan vendor:publish --provider="AhmedAliraqi\LaravelMediaUploader\Providers\UploaderServiceProvider" --tag="config"

This is the default content of the config file:

<?php

return [
    'documents_mime_types' => [
        'application/msword',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document', // .doc & .docx
        'application/vnd.ms-powerpoint',
        'application/vnd.openxmlformats-officedocument.presentationml.presentation', // .ppt & .pptx
        'application/vnd.ms-excel',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', // .xls & .xlsx
        'text/plain',
        'application/pdf',
        'application/zip',
        'application/x-rar',
        'application/x-rar-compressed',
        'application/octet-stream',
    ],
];

Use HasUploader trait in your model:

<?php

namespace App;


use Spatie\MediaLibrary\HasMedia\HasMedia;
use Spatie\MediaLibrary\HasMedia\HasMediaTrait;
use AhmedAliraqi\LaravelMediaUploader\Entities\Concerns\HasUploader;

class Blog extends Model implements HasMedia
{
    use HasMediaTrait, HasUploader;
    ...
}

In your controller use addAllMediaFromTokens() method to assign the uploaded media to model using the generated tokens:

class BlogController extends Controller
{
        public function store(Request $request)
        {
            $blog = Blog::create($request->all());
            
            $blog->addAllMediaFromTokens();
    
            return back();
        }
}

If you do not add any arguments in addAllMediaFromTokens() method will add all tokens in request('media') with any collection.

If you want to save specific collection name add it to the second argument.

// specified collection name
$blog->addAllMediaFromTokens([], 'pictures');

// specified tokens
$blog->addAllMediaFromTokens($request->input('tokens', []), 'pictures');

Front End Basic U

Or Install Component Via NPM

npm i laravel-file-uploader --save-dev

Now you should register the component in your resources/app.js:

// app.js

import FileUploader from 'laravel-file-uploader';

Vue.use(FileUploader);

Usage

<file-uploader :media="{{ $user->getMediaResource('avatars') }}"
               :max="1"
               collection="avatars"
               :tokens="{{ json_encode(old('media', [])) }}"
               label="Upload Avatar"
               notes="Supported types: jpeg, png,jpg,gif"
               accept="image/jpeg,image/png,image/jpg,image/gif"
></file-uploader>

Attributes

AttributeRuleTypeDescription
mediaoptional – default: []arrayused to display an existing files
maxoptional – default:12intthe maximum uploaded files – if 1 will not me multiple select
acceptoptional – default: *stringthe accepted mime types
notesoptional – default nullstringthe help-block that will be displayed under the files
labeloptional – default nullstringthe label of the uploader
collectionoptional – default defaultstringthe media library collection that the file will store in
tokensoptional – default: []arraythe recently uploaded files tokens, used to display recently uploaded files in validation case

Using with BsForm

This uploader support laravel-bootstrap-forms you can use the image custom component instead of vue html tag:

{{ BsForm::image('avatar')->collection('avatars')->files($user->getMediaResource('avatars')) }}
{{ BsForm::image('avatar')->max(3)->collection('avatars')->files($user->getMediaResource('avatars')) }}
{{ BsForm::image('avatar')->collection('avatars') }}

Note: do not forget to add Cron job in your server to remove the expired temporary media.

* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1

API

Upload Files

  • endpoint: /api/uploader/media/upload
  • method: POST
  • body:
    • files[]: multipart form data
  • response:

Display Recently Uploaded Files

  • endpoint: /api/uploader/media
  • method: GET
  • params:
    • tokens[]: temporary token
  • response:

Delete Files

  • endpoint: /api/uploader/media/{id}
  • method: DELETE
  • response:
Please find example here

About OakML

Hi we are enthusiastic developers team, we try to serve some good idea to open source community

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!