This package used to upload files using laravel-media-library before saving model.

Overview

Laravel Media Uploader

Build Status StyleCI Total Downloads Latest Stable Version License

This package used to upload files using laravel-media-library before saving model.

Uploader

In this package all uploaded media will be processed.

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

Requirements

  • PHP >= 7.4
  • You should be ensured that the ffmpeg was installed on your server

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"

If you want to customize validation translations, you should publish the lang files:

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

This is the default content of the config file:

<?php

return [
    /*
     * Regenerate uploaded media after assign to model
     */
    'regenerate-after-assigning' => true,

    '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\InteractsWithMedia;
use Spatie\MediaLibrary\MediaCollections\Models\Media;
use Spatie\MediaLibrary\HasMedia;
use AhmedAliraqi\LaravelMediaUploader\Entities\Concerns\HasUploader;

class Blog extends Model implements HasMedia
{
    use InteractsWithMedia, 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 Usage

<div id="app">
    <file-uploader
            :unlimited="true"
            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>
</div>

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/laravel-file-uploader"></script>
<script>
  new Vue({
    el: '#app'
  })
</script>
Or Install Component Via NPM
npm i laravel-file-uploader --save-dev

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

// app.js

import FileUploader from 'laravel-file-uploader';

Vue.use(FileUploader);

Usage

<file-uploader :media="{{ $user->getMediaResource('avatars') }}"
               :unlimited="true"
               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
Attribute Rule Type Description
media optional - default: [] array used to display an existing files
unlimited optional - default:false boolean upload unlimited files - if let it false will not be multiple select
max optional - default:12 int the maximum uploaded files - if 1 will not me multiple select
accept optional - default: * string the accepted mime types
form optional - default: false string the form id of the uploaded media
notes optional - default null string the help-block that will be displayed under the files
label optional - default null string the label of the uploader
collection optional - default default string the media library collection that the file will store in
tokens optional - default: [] array the recently uploaded files tokens, used to display recently uploaded files in validation case
max-width optional - default: 1200 string The maximum width of uploaded image
max-height optional - default: 1200 string The maximum height of uploaded image

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::audio('audio')->collection('audios')->files($user->getMediaResource('audios')) }}
{{ BsForm::video('video')->collection('videos')->files($user->getMediaResource('videos')) }}
{{ BsForm::media('media')->collection('videos')->accept('video/*')->files($user->getMediaResource('videos')) }}
{{ BsForm::image('avatar')->max(3)->collection('avatars')->files($user->getMediaResource('avatars')) }}
{{ BsForm::image('avatar')
    ->max(3)
    ->collection('avatars')
    ->maxWidth(500)
    ->maxHeight(500)
    ->files($user->getMediaResource('avatars')) }}
{{ BsForm::image('image')->unlimited()->files($user->getMediaResource()) }}
{{ 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

Note: Do not forget to store the csrf token in an HTML meta tag:

<meta name="csrf-token" content="{{ csrf_token() }}">

API

  • Upload Files
    • endpoint: /api/uploader/media/upload
    • method: POST
    • body:
      • files[]: multipart form data
    • response:
      • upload response
  • Display Recently Uploaded Files
    • endpoint: /api/uploader/media
    • method: GET
    • params:
      • tokens[]: temporary token
    • response:
      • response
  • Delete Files
    • endpoint: /api/uploader/media/{id}
    • method: DELETE
    • response:
      • response
Comments
  • Add Support For php 8.0

    Add Support For php 8.0

    @AbdullahFaqeir Can You fix php 8.0 support and bump laravel-medialibrary to ^9.0 if you have a free time ? Can you fix php 8.0 support and bump laravel-medialibrary to ^ 9.0 if you have free time? Unfortunately, I'm very busy right now, and don't have much time 😔

    opened by ahmed-aliraqi 8
  • Upload multiple files

    Upload multiple files

    Hi, Thanks for this nice package, I find some problem when i try to upload multiple files image

    first file upload normaly, but next files make validation error errors: {file: ["The file is not supported."]}

    i have latest laravel What it could be the mistake ?

    Thanks.

    bug 
    opened by demeus 7
  • Tailwind CSS for v2.0.0

    Tailwind CSS for v2.0.0

    Hello, I don't know why enforcing us to use Tailwind CSS in v2.0.0 ? Is there any way to choose or edit css for images preview ? Here how it looks (Bootstrap 4) : tomediauploader

    opened by AEK-BKF 3
  • subfolder problem

    subfolder problem

    If the site does not work under root, there is a problem in the subfolders. The xhr request does not use APP_URL.

    example APP_URL=http://abc.com/laravel/

    post request is sent to http://abc.com/

    opened by haytefli92 3
  • How to use with inertiajs

    How to use with inertiajs

    I still do not understand very well how it works but with inertiajs and vue as a view I cannot get the tokens of the images or files.

    And I don't know if it can be improved or explained better in the documentation, since I see that it is a very practical and great tool

    opened by EfrenColin 2
  • Questions about authentication & routes & design customization

    Questions about authentication & routes & design customization

    Hello, Thanks for your effort. I have four questions:

    • How can we apply some kind of authentication to the routes, I want only admins to upload files?
    • How can we disable some endpoint or delete it? I don't want the users to delete any file at all. we use soft-delete
    • How can we customize the UI as I already have a design?
    • I guess this package works well with S3. can you confirm, please?

    Thanks.

    opened by AhmedNourJamalElDin 2
  • Error on production env : Use of undefined constant STDIN

    Error on production env : Use of undefined constant STDIN

    Hi again, Please, I deployed your package on live server, but I get this error when I upload images :

    ErrorException
    Use of undefined constant STDIN - assumed 'STDIN' (this will throw an Error in a future version of PHP)
    

    Please see attached. Thanks.

    Laravel version 6.18.40 PHP version 7.4.9

    Screenshot_2020-09-20 🧨 Use of undefined constant STDIN - assumed 'STDIN' (this will throw an Error in a future version of

    opened by AEK-BKF 2
  • Is there any way to validate the uploaded file during uploading(runtime)

    Is there any way to validate the uploaded file during uploading(runtime)

    Hello Ahmed,

    First of all, Thanks for your great work, I really appreciate it.

    I am wondering if this package could validate the uploaded file before uploading the file because someone can upload a wrong mime type with a big size and after waiting some time, he will figure that his uploaded file does not meet the requirement that I have defined in the backend.

    Thanks again.

    opened by 109-marzouk 1
  • compatibility issue with laravel-medialibray custom directory structure

    compatibility issue with laravel-medialibray custom directory structure

    Hi, First of all I want to say thank you for such a great package! it's a life savior!!

    Now, this works perfect if we use default directory structure for media, however I'm using a custom directory structure which is as follows:

    protected function getBasePath(Media $media): string { return "{$media->model->getTable()}/{$media->model->id}/{$media->getKey()}"; }

    to organize media by models. however this package does not work with the custom directory structure, when I try to upload some media the package creates a new folder called temporary_files and never store files in the custom directory. so when I fetch media for my collection it could not find the files.

    Again, Thank you so much for such an amazing work!

    opened by amshehzad 1
  • Need Help

    Need Help

    Hi,

    Is there any way to set name and description for each file before uploading ? Something like this :

    $mediaItem = $newsItem
        ->addMedia($pathToFile)
        ->withCustomProperties(['name' => 'test', 'description' => 'something...', ... ])
        ->toMediaCollection();
    

    Thanks.

    opened by AEK-BKF 1
  • Images Uploading issue

    Images Uploading issue

    Hi, Thanks for this nice package, I've just installed it on L^6.2 every thing looks fine (see attached) But once I select any image it wont be shown ! What it could be the mistake ?

    Thanks.

    Screenshot_2020-07-04 inventory - producttemplate Update

    opened by AEK-BKF 1
  • Regenerate media after assigning doesn't work in production

    Regenerate media after assigning doesn't work in production

    Hi,

    There's a problem in regenerating media after assigning it to a model in production mode, since there is a warning that asks you whether you're sure to do this command.

    This warning confirmation is the reason why Artisan::call('media-library:regenerate') isn't working in production mode.

    To circumvent the warning, you can use the --force flag like so:

    Artisan::call('media-library:regenerate', [
       '--ids' => implode(',', $mediaIds),
       '--force' => true,
    ]);
    
    opened by AbdallaMohammed 0
Releases(v6.3.5)
Owner
Ahmed Fathy
Full Stack Developer
Ahmed Fathy
Upload File Library For PHP ( Simple & Easy User )

Upload File Library For Backend/ServerSide PHP ( Simple & Easy For Use ), Support Multiple Upload

Lamhot Simamora 1 Oct 12, 2021
ORM-based file upload package for php.

#Stapler Note: If you've previously been using this package, then you've been using it with Laravel. This package is no longer directly coupled to the

Code Sleeve 541 Dec 30, 2022
FIle Uploader is a php package to aid fast , easy and safe file upload

FILE UPLOADER FIle Uploader is a php package to aid fast , easy and safe file upload installation composer require codad5/file-helper Features Fast an

Aniezeofor Chibueze Michael 2 Sep 3, 2022
A PHP library to deal with all those media services around, parsing their URLs and displaying their audios/videos.

MediaEmbed A utility library that generates HTML embed tags for audio or video located on a given URL. It also parses and validates given media URLs.

Mark Sch. 165 Nov 10, 2022
A "Vuejs & Laravel" Media Manager With Tons of Features

Laravel Media Manager Installation Config Features Events Usage Installation composer require ctf0/media-manager publish the package assets with php a

Muah 783 Dec 29, 2022
Media gallery with CKEditor, TinyMCE and Summernote support. Built on Laravel file system.

Documents ・ Installation ・ Integration ・ Config ・ Customization ・ Events ・ Upgrade ・ Demo ・ FAQ Features File upload and management Uploading validati

UniSharp 1.9k Jan 1, 2023
Basic anonymous and registered upload storage for temporary share file self hosted.

TMPShareX Basic anonymous and registered upload storage for temporary share file self hosted. Server Requirement PHP 7.4.8 [Support PHP 8] Nginx 1.19.

Sandy Hermansyah 1 Feb 3, 2022
PictShare is an open source image, mp4, pastebin hosting service with a simple resizing and upload API that you can host yourself.

PictShare is an open source image, mp4, pastebin hosting service with a simple resizing and upload API that you can host yourself.

Haschek Solutions 709 Jan 3, 2023
Analyze content to determine the appropriate Internet media type

Canal Content analysis for the purpose of determining Internet media types. Requirements PHP 5.3+ Installation Through Composer as dflydev/canal. Usag

dflydev 34 Feb 11, 2022
FileNamingResolver - A lightweight library which helps to resolve a file/directory naming of uploaded files using various naming strategies

FileNamingResolver - A lightweight library which helps to resolve a file/directory naming of uploaded files using various naming strategies

Victor Bocharsky 111 May 19, 2022
PHP library that provides a filesystem abstraction layer − will be a feast for your files!

Gaufrette Gaufrette provides a filesystem abstraction layer. Why use Gaufrette? Imagine you have to manage a lot of medias in a PHP project. Lets see

KNP Labs 2.4k Jan 7, 2023
This small PHP package assists in the loading and parsing of VTT files.

VTT Transcriptions This small PHP package assists in the loading and parsing of VTT files. Usage use Laracasts\Transcriptions\Transcription; $transcr

Laracasts 52 Nov 28, 2022
PHP runtime & extensions header files for PhpStorm

phpstorm-stubs STUBS are normal, syntactically correct PHP files that contain function & class signatures, constant definitions, etc. for all built-in

JetBrains 1.2k Dec 25, 2022
ANTLR (ANother Tool for Language Recognition) is a powerful parser generator for reading, processing, executing, or translating structured text or binary files.

ANTLR (ANother Tool for Language Recognition) is a powerful parser generator for reading, processing, executing, or translating structured text or binary files. It's widely used to build languages, tools, and frameworks. From a grammar, ANTLR generates a parser that can build parse trees and also generates a listener interface (or visitor) that makes it easy to respond to the recognition of phrases of interest.

Antlr Project 13.6k Jan 6, 2023
Tailwind plugin to generate purge-safe.txt files

Tailwind plugin to generate safelist.txt files With tailwind-safelist-generator, you can generate a safelist.txt file for your theme based on a set of

Spatie 89 Dec 23, 2022
Associate files with Eloquent models

Associate files with Eloquent models This package can associate all sorts of files with Eloquent models. It provides a simple API to work with. To lea

Spatie 5.2k Jan 4, 2023
A python program to cut longer MP3 files (i.e. recordings of several songs) into the individual tracks.

I'm writing a python script to cut longer MP3 files (i.e. recordings of several songs) into the individual tracks called ReCut. So far there are two

Dönerspiess 1 Oct 27, 2021
A Flysystem proxy adapter that enables compression and encryption of files and streams on the fly

Slam / flysystem-compress-and-encrypt-proxy Compress and Encrypt files and streams before saving them to the final Flysystem destination. Installation

Filippo Tessarotto 27 Jun 4, 2022