Plank/Laravel-Mediable

TravisCI Coveralls SensioLabsInsight StyleCI Packagist

Laravel-Mediable is a package for easily uploading and attaching media files to models with Laravel 5.

Features

  • Filesystem-driven approach is easily configurable to allow any number of upload directories with different accessibility.
  • Many-to-many polymorphic relationships allow any number of media to be assigned to any number of other models without any need to modify the schema.
  • Attach media to models with tags, to set and retrieve media for specific purposes, such as 'thumbnail', 'featured image', 'gallery' or 'download'.
  • Easily query media and restrict uploads by MIME type, extension and/or aggregate type (e.g. image for jpeg, png or gif).

Installation

Add the package to your Laravel app using composer.

$ composer require plank/laravel-mediable

Register the package’s servive provider in config/app.php.

'providers' => [
    //...
    Plank\Mediable\MediableServiceProvider::class,
    //...
];

The package comes with a Facade for the image uploader, which you can optionally register as well.

'aliases' => [
    //...
    'MediaUploader' => Plank\Mediable\MediaUploaderFacade::class,
    //...
]

Publish the config file (config/mediable.php) and migration file (database/migrations/####_##_##_######_create_mediable_tables.php) of the package using artisan.

$ php artisan vendor:publish --provider="Plank\Mediable\MediableServiceProvider"

Run the migrations to add the required tables to your database.

$ php artisan migrate

Configuration

Disks

Laravel-Mediable is built on top of Laravel’s Filesystem component. Before you use the package, you will need to configure the filesystem disks where you would like files to be stored in config/filesystems.php. Learn more about filesystem disk.

An example setup with one private disk (local) and one publicly accessible disk (uploads):

//...
'disks' => [
    'local' => [
        'driver' => 'local',
        'root'   => storage_path('app'),
    ],

    'uploads' => [
        'driver' => 'local',
        'root'   => public_path('uploads'),
    ],
]
//...

Once you have set up as many disks as you need, edit config/mediable.php to authorize the package to use the disks you have created.

//...
/*
 * Filesystem disk to use if none is specified
 */
'default_disk' => 'uploads',

/*
 * Filesystems that can be used for media storage
 */
'allowed_disks' => [
    'uploads',
],
//...

Validation

The config/mediable.php offers a number of options for configuring how media uploads are validated. These values serve as defaults, which can be overridden on a case-by-case basis for each MediaUploader instance.

//...
/*
 * The maximum file size in bytes for a single uploaded file
 */
'max_size' => 1024 * 1024 * 10,

/*
 * What to do if a duplicate file is uploaded. Options include:
 *
 * * 'increment': the new file's name is given an incrementing suffix
 * * 'replace' : the old file and media model is deleted
 * * 'error': an Exception is thrown
 *
 */
'on_duplicate' => Plank\Mediable\MediaUploader::ON_DUPLICATE_INCREMENT,

/*
 * Reject files unless both their mime and extension are recognized and both match a single aggregate type
 */
'strict_type_checking' => false,

/*
 * Reject files whose mime type or extension is not recognized
 * if true, files will be given a type of `'other'`
 */
'allow_unrecognized_types' => false,

/*
 * Only allow files with specific MIME type(s) to be uploaded
 */
'allowed_mime_types' => [],

/*
 * Only allow files with specific file extension(s) to be uploaded
 */
'allowed_extensions' => [],

/*
 * Only allow files matching specific aggregate type(s) to be uploaded
 */
'allowed_aggregate_types' => [],
//...

Aggregate Types

Laravel-Mediable provides functionality for handling multiple kinds of files under a shared aggregate type. This is intended to make it easy to find similar media without needing to constantly juggle multiple MIME types or file extensions.

The package defines a number of common file types in the config file (config/mediable.php). Feel free to modify the default types provided by the package or add your own. Each aggregate type requires a key used to identify the type and a list of MIME types and file extensions that should be recognized as belonging to that aggregate type. For example, if you wanted to add an aggregate type for different types of markup, you could do the following.

//...
'aggregate_types' => [
    //...
    'markup' => [
        'mime_types' => [
            'text/markdown',
            'text/html',
            'text/xml',
            'application/xml',
            'application/xhtml+xml',
        ],
        'extensions' => [
            'md',
            'html',
            'htm',
            'xhtml',
            'xml'
        ]
    ],
    //...
]
//...

Note: a MIME type or extension could be present in more than one aggregate type’s definitions (the system will try to find the best match), but each Media record can only have one aggregate type.

Extending functionality

The config/mediable.php file lets you specify a number of classes to be use for internal behaviour. This is to allow for extending some of the the default classes used by the package or to cover additional use cases.

/*
 * FQCN of the model to use for media
 *
 * Should extend Plank\Mediable\Media::class
 */
'model' => Plank\Mediable\Media::class,

/*
 * List of adapters to use for various source inputs
 *
 * Adapters can map either to a class or a pattern (regex)
 */
'source_adapters' => [
    'class' => [
        Symfony\Component\HttpFoundation\File\UploadedFile::class => Plank\Mediable\SourceAdapters\UploadedFileAdapter::class,
        Symfony\Component\HttpFoundation\File\File::class => Plank\Mediable\SourceAdapters\FileAdapter::class,
    ],
    'pattern' => [
        '^https?://' => Plank\Mediable\SourceAdapters\RemoteUrlAdapter::class,
        '^/' => Plank\Mediable\SourceAdapters\LocalPathAdapter::class
    ],
],

/*
 * List of URL Generators to use for handling various filesystem disks
 */
'url_generators' => [
    'local' => Plank\Mediable\UrlGenerators\LocalUrlGenerator::class,
    's3' => Plank\Mediable\UrlGenerators\S3UrlGenerator::class,
],

Uploading Files

The easiest way to upload media to your server is with the MediaUploader class, which handles validating the file, moving it to its destination and creating a Media record to reference it. You can get an instance of the MediaUploader using the Facade and configure it with a fluent interface.

To upload a file to the root of the default disk (set in config/mediable.php), all you need to do is the following:

<?php
use MediaUploader; //use the facade
$media = MediaUploader::fromSource($request->file('thumbnail'))->upload();

The fromSource() method will accept either

  • an instance of Symfony\Component\HttpFoundation\File.
  • an instance of Symfony\Component\HttpFoundation\UploadedFile.
  • a URL as a string, beginning with http:// or https://.
  • an absolute path as a string, beginning with /.

Specifying Destination

You can customize where the uploader will put the file on your server before you invoke the upload() method.

<?php
$uploader = MediaUploader::fromSource($request->file('thumbnail'))

// specify a disk to use instead of the default
->setDisk('s3');

// place the file in a directory relative to the disk root
->setDirectory('user/john/profile')

// alternatively, specify both the disk and directory at once
->toDestination('s3', 'user/john/profile')

// Overide the filename of the source file
->setFilename('profile.jpg')

->upload();

Validation

The MediaUpload will perform a number of validation checks on the source file. If any of the checks fail, a Plank\Mediable\MediaUploaderException will be through with a message indicating why the file was rejected.

You can override the most validation configuration values set in config/mediable.php on a case-by-case basis using the same fluent interface.

<?php
$media = MediaUploader::fromSource($request->file('image'))

    // model class to use
    ->setModelClass(MediaSubclass::class)

    // maximum filesize in bytes
    ->setMaximumSize(99999)

    // how to handle a file that already exists at the destination
    ->setOnDuplicateBehavior(Media::ON_DUPLICATE_REPLACE)

    // whether the aggregate type must match both the MIME type and extension
    ->setStrictTypeChecking(true)

    // whether to allow the 'other' aggregate type
    ->setAllowUnrecognizedTypes(true)

    // only allow files of specific MIME types
    ->setAllowedMimeTypes(['image/jpeg'])

    // only allow files of specifc extensions
    ->setAllowedExtensions(['jpg', 'jpeg'])

    // only allow files of specific aggregate types
    ->setAllowedAggregateTypes(['image'])

    ->upload();

Handling Media

Add the Mediable trait to any Eloquent models that you would like to be able to attach media to.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Plank\Mediable\Mediable;

class Post extends Model
{
    use Mediable;

    // ...
}

Attaching Media

You can attach media to your Mediable model using the attachMedia() method. This method takes a second argument, specifying one or more tags which define the relationship between the model and the media. Tags are simply strings; you can use any value you need to describe how the model should use its attached media.

<?php
$post = Post::first();
$post->attachMedia($media, 'thumbnail');

You can attach multiple media to the same tag with a single call. The attachMedia() method accept any of the following for its first parameter:

  • a numeric or string id
  • an instance of \Plank\Mediable\Media
  • an array of ids
  • an instance of \Illuminate\Database\Eloquent\Collection
<?php
$post->attachMedia([$media1->getKey(), $media2->getKey()], 'gallery');

You can also assign media to multiple tags with a single call.

<?php
$post->attachMedia($media, ['gallery', 'featured']);

Replacing Media

Media and Mediable models share a many-to-many relationship, which allows for any number of media to be added to any key. The attachMedia() method will add a new association, but will not remove any existing associations to other media. If you want to replace the media previously attached to the specified tag(s) you can use the syncMedia() method. This method accepts the same inputs as attachMedia().

<?php
$post->syncMedia($media, 'thumbnail');

Retrieving Media

You can retrieve media attached to a file by refering to the tag to which it was previously assigned.

<?php
$media = $post->getMedia('thumbnail');

This returns a collection of all media assigned to that tag. In cases where you only need one Media entity, you can instead use firstMedia().

<?php
$media = $post->firstMedia('thumbnail');
// shorthand for
$media = $post->getMedia('thumbnail')->first();

If you specify an array of tags, the method will return media is attached to any of those tags. Set the $match_all parameter to true to tell the method to only return media that are attached to all of the specified tags.

<?php
$post->getMedia(['header', 'footer']); // get media with either tag
$post->getMedia(['header', 'footer'], true); //get media with both tags
$post->getMediaMatchAll(['header', 'footer']); //alias

You can also get all media attached to a model, grouped by tag.

<?php
$post->getAllMediaByTag();

Checking for the Presence of Media

You can verify if a model has one or more media assigned to a given tag with the hasMedia() method.

<?php
if($post->hasMedia('thumbnail')){
    // ...
}

You can specify multiple tags when calling either method, which functions similarly to getMedia(). The method will return true if getMedia() passed the same parameters would return any instances.

You also can also perform this check using the query builder.

<?php
$posts = Post::whereHasMedia('thumbnail')->get();

Detaching Media

You can remove a media record from a model with the detachMedia() method.

<?php
$post->detachMedia($media); // remove media from all tags
$post->detachMedia($media, 'feature'); //remove media from specific tag
$post->detachMedia($media, ['feature', 'thumbnail']); //remove media from multiple tags

You can also remove all media assigned to one or more tags.

<?php
$post->detachMediaTags('feature');
$post->detachMediaTags(['feature', 'thumbnail']);

Loading Media

When dealing with any model relationships, taking care to avoid running into the “N+1 problem” is an important optimization consideration. The N+1 problem can be summed up as a separate query being run for the related content of each record of the parent model. Consider the following example:

<?php
$posts = Post::limit(10)->get();
foreach($posts as $post){
    echo $post->firstMedia('thumbnail')->getUrl();
}

Assuming there are at least 10 Post records available, this code will execute 11 queries: oen query to load the 10 posts from the database, then another 10 queries to load the media for each of the post records indiviudally. This will slow down the rendering of the page.

There are a couple of approaches that can be taken to preload the attached media in order to avoid this issue.

Eager Loading

The Eloquent query builder’s with() method is the prefered way to eager load related models. This package also provides an alias.

<?php
$posts = Post::with('media')->get();
// or
$posts = Post::withMedia()->get();

You can also load only media attached to specific tags.

<?php
$posts = Post::withMedia(['thumbnail', 'featured']); // attached to either tags
$posts = Post::withMediaMatchAll(['thumbnail', 'featured']); // attached to both tags

Note: if using this approach to conditionally preload media by tag, you will not be able to access media with other tags using getMedia() without first reloading the media relationship on that record.

Lazy Eager Loading

If you have already loaded models from the database, you can still load relationships with the load() method of the Eloquent Collection class. The package also provides an alias.

<?php
$posts = Post::all();
// ...

$posts->load('media');
// or
$posts->loadMedia();

You can also load only media attached to specific tags.

<?php
$posts->loadMedia(['thumbnail', 'featured']); // attached to either tag
$posts->loadMediaMatchAll(['thumbnail', 'featured']); // attached to both tags

The same method is available as part of the Mediable trait, and can be used directly on a model instance.

<?php
$post = Post::first();
$post->loadMedia();
$post->loadMedia(['thumbnail', 'featured']); // attached to either tag
$post->loadMediaMatchAll(['thumbnail', 'featured']); // attached to both tags

Any of these methods can be used to reload the media relationship of the model.

Note: if using this approach to conditionally preload media by tag, you will not be able to access media with other tags using getMedia() without first reloading the media relationship on that record.

Automatic Rehydration

By default, Mediable models will automatically reload their media relationship the next time the media at a given tag is accessed after that tag is modified.

The attachMedia(), syncMedia(), detachMedia(), and detachMediaTags() methods will mark any tags passed as being dirty, while the hasMedia() getMedia(), firstMedia(), getAllMediaByTag(), and getTagsForMedia() methods will execute loadMedia() to reload all media if they attempt to read a dirty tag.

For example:

<?php
$post->loadMedia();
$post->getMedia('gallery'); // returns an empty collection
$post->getMedia('thumbnail'); // returns an empty collection
$post->attachMedia($media, 'gallery'); // marks the gallery tag as dirty

$post->getMedia('thumbnail'); // still returns an empty collection
$post->getMedia('gallery'); // performs a `loadMedia()`, returns a collection with $media

You can enable or disable this behaviour on a class-by-class basis by adding the $rehydrates_media property to your Mediable model.

<?php
// ...

class Post extends Model
{
    use Mediable;

    protected $rehydrates_media = false;

    // ...
}

You can also set the application-wide default behaviour in config/mediable.php.

'rehydrate_media' => true,

Deleting Mediables

You can delete mediable model with standard Eloquent model delete() method. This will also detach any associated Mediable models.

<?php
$post->delete();

Note: The delete() method on the query builder will not purge media relationships.

<?php
Media::where(...)->delete(); //will not detach relationships
Soft Deletes

If your Mediable class uses Laravel’s SoftDeletes trait, the model will only detach its media relationships if forceDelete() is used.

You can change the detach_on_soft_delete setting to true in config/mediable.php to have relationships automatically detach when either the Media record or Mediable model are soft deleted.

Using Media

Media Paths & URLs

Media records keep track of the location of their file and are able to generate a number of paths and URLs relative to the file. Consider the following example, given a Media instance with the following attributes:

[
        'disk' => 'uploads',
        'directory' => 'foo/bar',
        'filename' => 'picture',
        'extension' => 'jpg'
        // ...
];

The following attributes and methods would be exposed:

<?php
$media->getAbsolutePath();
// /var/www/site/public/uploads/foo/bar/picture.jpg

$media->getUrl();
// http://localhost/uploads/foo/bar/picture.jpg

$media->getDiskPath();
// foo/bar/picture.jpg

$media->directory;
// foo/bar

$media->basename;
// picture.jpg

$media->filename;
// picture

$media->extension;
// jpg

Querying Media

If you need to query the media table directly, rather than through associated models, the Media class exposes a few helpful methods for the query builder.

<?php
Media::inDirectory('uploads', 'foo/bar');
Media::inOrUnderDirectory('uploads', 'foo');
Media::forPathOnDisk('uploads', 'foo/bar/picture.jpg');
Media::whereBasename('picture.jpg');

Moving Media

You should taking caution if manually changing a media record’s attributes, as you record and file could go out of sync.

You can change the location of a media file on disk. You cannot move a media to a different disk this way.

<?php
$media->move('new/directory');
$media->move('new/directory', 'new-filename');
$media->rename('new-filename');

Deleting Media

You can delete media with standard Eloquent model delete() method. This will also delete the file associated with the record and detach any associated Mediable models.

<?php
$media->delete();

Note: The delete() method on the query builder will not delete the associated file. It will still purge relationships due to the cascading foreign key.

<?php
Media::where(...)->delete(); //will not delete files
Soft Deletes

If you subclass the Media class and add Laravel’s SoftDeletes trait, the media will only delete its associated file and detach its relationship if forceDelete() is used.

You can change the detach_on_soft_delete setting to true in config/mediable.php to have relationships automatically detach when either the Media record or Mediable model are soft deleted.

Aggregate Types

Laravel-Mediable provides functionality for handling multiple kinds of files under a shared aggregate type. This is intended to make it easy to find similar media without needing to constantly juggle multiple MIME types or file extensions. For example, you might want to query for an image, but not care if it is in JPEG, PNG or GIF format.

<?php
Media::where('aggregate_type', Media::TYPE_IMAGE)->get();

You can use this functionality to restrict the uploader to only accept certain types of files.

<?php
MediaUploader::fromSource($request->file('thumbnail'))
    ->toDestination('uploads', '')
    ->setAllowedAggregateTypes([Media::TYPE_IMAGE, Media::TYPE_IMAGE_VECTOR])
    ->upload()

To customize the aggregate type definitions for your project, see Configuring Aggregate Types.

Artisan Commands

This package provides a handful of artisan commands to help keep you filesystem and database in sync.

Create a media record in the database for any files on the disk that do not already have a record. This will apply any type restrictions in the mediable configuration file.

$ php artisan media:import [disk]

Delete any media records representing a file that no longer exists on the disk.

$ php artisan media:purge [disk]

To perform both commands together, you can use:

$ php artisan media:sync [disk]