Coder Social home page Coder Social logo

laravel-medialibrary's Introduction

laravel-medialibrary

Latest Version Software License Build Status Quality Score Total Downloads

This packages makes it easy to add and manage media associated with models.

Install

Require the package through Composer

$ composer require spatie/laravel-medialibrary

Register the service provider and the MediaLibrary facade.

// config/app.php
'providers' => [
    ...
    'Spatie\MediaLibrary\MediaLibraryServiceProvider',
];
// config/app.php
'aliases' => [
    ...
    'MediaLibrary' => 'Spatie\MediaLibrary\MediaLibraryFacade',
];

Next publish the configuration

$ php artisan vendor:publish --provider="Spatie\MediaLibrary\MediaLibraryServiceProvider"

You can separately publish the config or the migration using the config or migrations tag.

Next run the migration for the Media table

$ php artisan migrate

The publicPath key in the configuration is where the generated images are stored. This is set to a sensible default already.

The globalImageProfiles is a way to set global image profiles. (These can be overwritten by a models image profiles).

Usage

Models have to use the MediaLibraryModelTrait to gain access to the needed methods.

Overview of methods

All examples assume $user = User::find(1);

getMedia

Return all media from a certain collection belonging to a $user.

$user->getMedia('images');

getMedia has an optionals $filters argument.

getFirstMedia

Returns only the first media-record from a certain collection belonging to a $user.

$user->getFirstMedia('images');

getFirstMediaURL

Returns the URL of the first media-item with given collectionName and profile

$user->getFirstMediaURL('images', 'small');

addMedia

Add a media-record using a file and a collectionName.

$user->addMedia('testImage.jpg', 'images');

addMedia has optional $preserveOriginal and $addAsTemporary arguments.

removeMedia

Remove a media-record ( and associated generated files) by its id

$user->removeMedia(1);

updateMedia

Update the media-records with given information ( and automatically reorder them).

$user->updateMedia([
    ['id' => 1, 'name' => 'updatedName'],
], 'images');

Facade

You can also opt to use the MediaLibrary-facade directly (which the trait uses).

add();
MediaLibrary::add($file, MediaLibraryModelInterface $model, $collectionName, $preserveOriginal = false, $addAsTemporary = false);

The same as addMedia but the model is an argument.

remove();
MediaLibrary::remove($id);

The same as removeMedia but without a bit of validation.

order();
MediaLibrary::order($orderArray, MediaLibraryModelInterface $model);

Reorders media-records (order_column) for a given model by the $orderArray. $orderArray should look like [1 => 4, 2 => 3, ... ] where the key is the media-records id and the value is what value order_column should get.

getCollection();
MediaLibrary::getCollection(MediaLibraryModelInterface $model, $collectionName, $filters);

Same as getMedia without the default $filters set to 'temp' => 1

cleanUp();
MediaLibrary::cleanUp();

Deletes all temporary media-records and associated files older than a day.

regenerateDerivedFiles();
MediaLibrary::regenerateDerivedFiles($media);

Removes all derived files for a media-record and regenerates them.

Simple example

We have a User-model. A user must be able to have pdf files associated with them.

Firstly, make use of the MediaLibraryModelTrait in your model.

class User extends Model {
    
    use MediaLibraryModelTrait;
    ...
}

Next you can add the files to the user like this:

$user->addMedia($pathToFile, 'pdfs');

Remove it like this:

$user->removeMedia($id);
//$id is the media-records id.

This will also delete the file so use with care.

Update it like this:

$updatedMedia = [
    ['id' => 1, 'name' => 'newName'],
];

$user->updateMedia($updatedMedia, 'pdfs');

Get media-records like this:

$media = $user->getMedia('pdfs');

Now you can loop over these to get the url's to the files.

foreach($media as $profileName => $mediaItem)
{
    $fileURL = $mediaItem->getAllProfileURLs();
}

// $fileURL will be ['original' => '/path/to/file.pdf]

In-depth example

Preparation

Let's say we have a User-model that needs to have images associated with it.

After installing the package (migration, config, facade, service provider) we add the MediaLibraryModelTrait to our User model.

This gives you access to all needed methods.

class User extends Model {
    
    use MediaLibraryModelTrait;
    ...
}

If you use this package for images ( like this example) the model should have the public $imageProfiles member.

Example:

public $imageProfiles = [
        'small'  => ['w' => '150', 'h' => '150', 'filt' => 'greyscale', 'shouldBeQueued' => false],
        'medium' => ['w' => '450', 'h' => '450'],
        'large'  => ['w' => '750', 'h' => '750' , 'shouldBeQueued' => true],
    ];

The shouldBeQueued-key is optional and will default to true if absent.

The MediaLibrary utilizes Glide so take a look at Glide's image api.

Adding media

Say our user uploads an image to the application that needs to have the versions specified in the User-model.

Firstly 'get' the user.

$user = User::find(1);

Then, use the trait to 'add the media'.

$pathToUploadedImage = storage_path('uploadedImage.jpg');
$user->addMedia($pathToUploadedImage, 'images');

This will generate all images specified in getImageProfileProperties and insert a record into the Media-table. The images will be placed in the path set in the publicPath in the config.

Updating media

Say we want to update some media records.

We need to give an array containing an array for each record that needs to be updated.

$updatedMedia = [
    ['id' => 1, 'name' => 'newName'],
    ['id' => 2, 'collection_name' => 'newCollectionName'],
];

$user->updateMedia($updatedMedia, 'images');

If the given collectionName doesn't check out an exception will be thrown. Media-record with id 1 will have its name updated and media-records with id 2 will have its collection_name updated.

Removing media

$user->removeMedia(1);

Remove a media-record and its associated files with removeMedia() and the id of the media-records as a parameter.

Displaying Media

Displaying media by passing 'media' to a view:

// In controller
$user = User::find(1);

$media = $user->getMedia('images');

return view('a_view')
    ->with(compact('media');

In your view, this would display all media from the images collection for a certain $user

@foreach($media as $mediaItem)

    @foreach($mediaItem->getAllProfileURLs() as $profileName => $imageURL)
    
        <img src="{{ url($imageURL) }}">
    
    @endforeach

@endforeach

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.

laravel-medialibrary's People

Contributors

freekmurze avatar matthiasdewinter avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.