Coder Social home page Coder Social logo

spatie / laravel-medialibrary Goto Github PK

View Code? Open in Web Editor NEW
5.6K 85.0 1.0K 8.27 MB

Associate files with Eloquent models

Home Page: https://spatie.be/docs/laravel-medialibrary

License: MIT License

PHP 99.70% Blade 0.30%
laravel php eloquent media upload images hacktoberfest

laravel-medialibrary's Introduction

Social Card of Laravel Media Library

Associate files with Eloquent models

Latest Version run-tests Total Downloads

This package can associate all sorts of files with Eloquent models. It provides a simple API to work with. To learn all about it, head over to the extensive documentation.

Here are a few short examples of what you can do:

$newsItem = News::find(1);
$newsItem->addMedia($pathToFile)->toMediaCollection('images');

It can handle your uploads directly:

$newsItem->addMedia($request->file('image'))->toMediaCollection('images');

Want to store some large files on another filesystem? No problem:

$newsItem->addMedia($smallFile)->toMediaCollection('downloads', 'local');
$newsItem->addMedia($bigFile)->toMediaCollection('downloads', 's3');

The storage of the files is handled by Laravel's Filesystem, so you can use any filesystem you like. Additionally, the package can create image manipulations on images and pdfs that have been added in the media library.

Spatie is a webdesign agency in Antwerp, Belgium. You'll find an overview of all our open source projects on our website.

Support us

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.

Documentation

You'll find the documentation on https://spatie.be/docs/laravel-medialibrary.

Find yourself stuck using the package? Found a bug? Do you have general questions or suggestions for improving the media library? Feel free to create an issue on GitHub, we'll try to address it as soon as possible.

If you've found a bug regarding security please mail [email protected] instead of using the issue tracker.

Testing

You can run the tests with:

./vendor/bin/pest

You can run the Github actions locally with act. You have to use a custom image for the ubuntu-latest platform to get PHP up and running properly. To run the tests locally, run:

act -P ubuntu-latest=shivammathur/node:latest

To run a specific workflow, for example run-tests.yml run:

act -P ubuntu-latest=shivammathur/node:latest -j run-tests

Upgrading

Please see UPGRADING for details.

Changelog

Please see CHANGELOG for more information what has changed recently.

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

A big thank you to Nicolas Beauvais for helping out with the issues on this repo.

And a special thanks to Caneco for the logo โœจ

Alternatives

License

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

laravel-medialibrary's People

Contributors

adrianmrn avatar ahmedofali avatar alexvanderbist avatar antonkomarev avatar arubacao avatar brendt avatar carusogabriel avatar cosmastech avatar dependabot[bot] avatar drbyte avatar erikn69 avatar firtzberg avatar freekmurze avatar gdebrauwer avatar github-actions[bot] avatar matthiasdewinter avatar nicolasbeauvais avatar nielsvanpach avatar omranic avatar patinthehat avatar rhincodon avatar rubenvanassche avatar sebastiandedeyne avatar squatto avatar szepeviktor avatar timvandijck avatar tofandel avatar tvke avatar willemvb avatar ziming avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

laravel-medialibrary's Issues

Move media directory to storage

Hi!

Do you think it is possible to manage media directory, as move it to storage directory ?
It makes my life easier when I deploy with Envoyer.io.

Thanks ;)

Question: Any way to preserve or specifiy folder structure?

Hello,

Right now the folder structure is the path we specifiy in media drive plus the id of media object plus the filename. Ex: /public/images/1/test.jpg

I want to modify the folder structure because i want to organize the folder. Now everything is inside one folder. For example i want to have path like: /public/images/reports/daily/1.jpg

/public/images part comes from the filesystem config file. We have to specifiy reports/daily part, maybe with toFolder method. Or with preserveFolderStructure we can keep the original structure.

We can discuss this and i can make a PR if you think this is a good idea.

Laravel 4.2?

Is there any way to make this work with Laravel 4.2?

[Testing] Update docs to show how library can be mocked

I was watching Jeff Way's unit testing episode recently and having successfully used this library I wondered how I could mock it in a similar fashion to JW and figured this would be a useful addition to the readme.

In my test I have the following:

// As per Jeff's tutorial
$file = m::mock(UploadedFile::class, [
    'getClientOriginalName'      => 'foo.png',
    'getClientOriginalExtension' => 'png'
]);

// Errors get thrown before we even call the AddPhotoToJob class if we don't mock these
$file->shouldReceive('getPath')->once()->andReturn('images/foo.png');
$file->shouldReceive('getFilename')->once()->andReturn('foo.png');
$file->shouldReceive('getMimeType')->once()->andReturn('image/png');

(new AddPhotoToJob($job, $file))->attach();

and it returns:

1) PhotosTest::it_adds_a_photo_into_storage
Spatie\MediaLibrary\Exceptions\FileDoesNotExist:

/home/vagrant/Code/DevSite/vendor/spatie/laravel-medialibrary/src/FileAdder/FileAdder.php:251
/home/vagrant/Code/DevSite/vendor/spatie/laravel-medialibrary/src/FileAdder/FileAdder.php:245
/home/vagrant/Code/DevSite/app/Repos/Photos/AddPhotoToJob.php:53
/home/vagrant/Code/DevSite/tests/Integration/PhotosTest.php:32

FAILURES!
Tests: 1, Assertions: 0, Errors: 1.

I have gotten the tests to green by placing a stub in storage and setting the path using storage_path but of course the library moves the file rendering the next test rerun useless unless I spin up another stub.

Just a little more documentation

Hi!

Thanks for your nice work to manage medias with models, it's really cool!

But, is it planned to write more documentation, I'm a little lost with only README file ...
Or maybe some live examples?

Thanks a lot!

Adding PNG Type

Hey,

I am requesting you allow the use of PNG Image Type, it would be very useful.

Thanks,

Cody

Functionality to add remote media links

Hi, yours is a great library and i am loving to use it.
I haws wondering how we can add remote urls as a media so it doesn't give file not found exception?
I am working on an app where you can upload your files or just add links to Youtube/vemeo or any direct images to the section and it will fetch from there.
I wanted to know if that is possible with your package?

Supporting URLs as linked media

Hi this is more of a question than anything on how easy it would be to adapt this package to store URL's of say blog posts or documents hosted on other sites.

Does this package allow for something like that currently or will could this be something that is added in the future. I just came across this today and it looks like a more fleshed out version of what I have on a current project. On the face of it looks like it does everything I'm looking for with the exception of storing URLs instead of actual file locations.

Thanks again, this package an others you guys have look great.

addMedia problem

Hello,

I try to add media to my model like this

$path = base_path('resources/uploads');
$fileName = uniqid('client_logo_') . '.' . $logo->getClientOriginalExtension();
$logo->move($path, $fileName);
$client->addMedia($path . DIRECTORY_SEPARATOR . $fileName)->preservingOriginal()->toCollection('clients');

But got the error

Not null violation: 7 ERROR: null value in column "model_id" violates not-null constraint (SQL: insert into "media" ("name", "file_name", "disk", "collection_name", "size", "custom_properties", "manipulations", "updated_at", "created_at") values (client_logo_55e6baae7ac9c, client_logo_55e6baae7ac9c.png, media, clients, 192991, [], [], 2015-09-02 09:00:30, 2015-09-02 09:00:30) returning "id")

Could you please check?

Best Regards
Dmitry

add softDelete to media model

I use soft delete for my models.
Now, when I delete items, they get soft deleted but media gets hard deleted.
So any chance to get a soft delete option in a future version?

extra DB queries

Hello,

I love this package but I encounter a little performance problem.
I don't know if it is my doing or a bug in the package.

I have the impression that for every media image that I display an extra DB query is executed requesting all columns from the parent model item. (see debug bar queries in attached image)

queries

In my app I do the following :

  • I request a collection of items. i.e. $photos = repo->all();
  • I lazy load the media objects attached to the items. i.e. $photos->load("media");
  • When I loop over the items, I see a DB query for all columns for every item. i.e. SELECT * FROM photos WHERE id = 1

Migration error

php artisan vendor:publish command incorrectly ticking

MediaLibraryServiceProvider.php file

$this->publishes([
            __DIR__.'/ToPublish/migrations/create_media_table.php' => base_path('database/migrations/'.$timestamp.'_create_media_table.php'),
        ], 'migrations');

$timestamp variables occurs because of multiple migration

2015_06_27_175650_create_media_table.php
2015_06_27_180010_create_media_table.php

vendor:publish not publishing in 5.1

I am testing your version from the next-gen branch at the moment and the config and migration don't get published unless I do a little change in the ServiceProvider even though I get a success message on publishing.

I have to change the $this->app->configPath and $this->app->basePath to config_path and database_path.

__DIR__.'/../resources/config/laravel-medialibrary.php' => $this->app->configPath('laravel-medialibrary.php'),
__DIR__.'/../resources/config/laravel-medialibrary.php' => config_path('laravel-medialibrary.php'),
__DIR__.'/../resources/migrations/create_media_table.php' => $this->app->basePath('database/migrations/'.$timestamp.'_create_media_table.php'),
__DIR__.'/../resources/migrations/create_media_table.php' => database_path('migrations/'.$timestamp.'_create_media_table.php'),

Profile sizes

In the Readme it says the getImageProfileProperties method can be placed on the Model to define profiles that will be created for each image associated with the model. Defining this however doesn't seem to do anything, and I can't find any calls to that method in the codebase. Am I missing something or is this just not implemented?

Global reusable images library

Hi, it looks like a great library, but it would be great to be able to reuse the same images in different models. So I suppose it needs many-to-many relations and but in this case it will be one single options set for images conversions for whole library... Maybe it's possible to make it as an option, something like global library. This way it will be able to create Wordpress like media library (which is I'm searching for Laravel).

Class 'CreateMediaTable' not found

Once installed (using Laravel 5.11) the migration refresh throws an exception :

$ art migrate:refresh --seed
PHP Fatal error:  Class 'CreateMediaTable' not found in /Users/loranger/Developer/projects/fairechier/vendor/laravel/framework/src/Illuminate/Database/Migrations/Migrator.php on line 324
PHP Stack trace:
PHP   1. {main}() /Users/loranger/Developer/projects/fairechier/artisan:0
PHP   2. Illuminate\Foundation\Console\Kernel->handle() /Users/loranger/Developer/projects/fairechier/artisan:36
PHP   3. Symfony\Component\Console\Application->run() /Users/loranger/Developer/projects/fairechier/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php:100
PHP   4. Symfony\Component\Console\Application->doRun() /Users/loranger/Developer/projects/fairechier/vendor/symfony/console/Application.php:126
PHP   5. Symfony\Component\Console\Application->doRunCommand() /Users/loranger/Developer/projects/fairechier/vendor/symfony/console/Application.php:195
PHP   6. Illuminate\Console\Command->run() /Users/loranger/Developer/projects/fairechier/vendor/symfony/console/Application.php:878
PHP   7. Symfony\Component\Console\Command\Command->run() /Users/loranger/Developer/projects/fairechier/vendor/laravel/framework/src/Illuminate/Console/Command.php:136
PHP   8. Illuminate\Console\Command->execute() /Users/loranger/Developer/projects/fairechier/vendor/symfony/console/Command/Command.php:259
PHP   9. Illuminate\Container\Container->call() /Users/loranger/Developer/projects/fairechier/vendor/laravel/framework/src/Illuminate/Console/Command.php:150
PHP  10. call_user_func_array:{/Users/loranger/Developer/projects/fairechier/vendor/laravel/framework/src/Illuminate/Container/Container.php:502}() /Users/loranger/Developer/projects/fairechier/vendor/laravel/framework/src/Illuminate/Container/Container.php:502
PHP  11. Illuminate\Database\Console\Migrations\RefreshCommand->fire() /Users/loranger/Developer/projects/fairechier/vendor/laravel/framework/src/Illuminate/Container/Container.php:502
PHP  12. Illuminate\Console\Command->call() /Users/loranger/Developer/projects/fairechier/vendor/laravel/framework/src/Illuminate/Database/Console/Migrations/RefreshCommand.php:44
PHP  13. Illuminate\Console\Command->run() /Users/loranger/Developer/projects/fairechier/vendor/laravel/framework/src/Illuminate/Console/Command.php:166
PHP  14. Symfony\Component\Console\Command\Command->run() /Users/loranger/Developer/projects/fairechier/vendor/laravel/framework/src/Illuminate/Console/Command.php:136
PHP  15. Illuminate\Console\Command->execute() /Users/loranger/Developer/projects/fairechier/vendor/symfony/console/Command/Command.php:259
PHP  16. Illuminate\Container\Container->call() /Users/loranger/Developer/projects/fairechier/vendor/laravel/framework/src/Illuminate/Console/Command.php:150
PHP  17. call_user_func_array:{/Users/loranger/Developer/projects/fairechier/vendor/laravel/framework/src/Illuminate/Container/Container.php:502}() /Users/loranger/Developer/projects/fairechier/vendor/laravel/framework/src/Illuminate/Container/Container.php:502
PHP  18. Illuminate\Database\Console\Migrations\ResetCommand->fire() /Users/loranger/Developer/projects/fairechier/vendor/laravel/framework/src/Illuminate/Container/Container.php:502
PHP  19. Illuminate\Database\Migrations\Migrator->reset() /Users/loranger/Developer/projects/fairechier/vendor/laravel/framework/src/Illuminate/Database/Console/Migrations/ResetCommand.php:69
PHP  20. Illuminate\Database\Migrations\Migrator->runDown() /Users/loranger/Developer/projects/fairechier/vendor/laravel/framework/src/Illuminate/Database/Migrations/Migrator.php:194
PHP  21. Illuminate\Database\Migrations\Migrator->resolve() /Users/loranger/Developer/projects/fairechier/vendor/laravel/framework/src/Illuminate/Database/Migrations/Migrator.php:215



  [Symfony\Component\Debug\Exception\FatalErrorException]
  Class 'CreateMediaTable' not found

Did I miss something ?

Add base64 support for `addMedia`

It would be good to work with WYSIWYG editor that send images as base64 fields.

I'll try to do a POC soon, then a PR.

Cf. welcoMattic#2

I don't know if it's in the scope of your package, then tell me! ๐Ÿ˜„

extension error on upload

hi guys,
i am trying your package as i think it is just what i need :)
i managed to instal and configure as your docs,
i am haing a problem uploading an image though

I am getting the following error:
ErrorException in MediaLibraryRepository.php line 165:
Undefined index: extension

in you repos, pathinfo() doesn't return the extension.
i am calling the addMedia with my model and not the facade.

$file = Input::file('image');
$collectionName = $news->getMediaCollectionName(); //method i created in my model
$news->addMedia($file, $collectionName);

getMedia() doesn't return media with collection set

I expected getMedia() to return all media regardless of collection name, but it doesn't turns out this way. If I did

$object->addMedia($file, $file->getMimeType());

$object->getMedia() returns me nothing.

Error with abstract method

I implemented the interface and trait to Laravel default User model and receive the following fatal error:
Class App\Models\User contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (Spatie\MediaLibrary\HasMedia::registerMediaConversions).

Target [Spatie\MediaLibrary\UrlGenerator\UrlGenerator] is not instantiable

I get this error after installing the package through composer. Seems like the UrlGenerator Interface can't be resolved from the App Container. Anyone else experiencing this? How can I fix this?
The error occurs when calling getUrl() on a Media object.

ErrorException in Container.php line 744:
Target [Spatie\MediaLibrary\UrlGenerator\UrlGenerator] is not instantiable.

In Laravel 5.1 uploaded file stores with temporary php name instead of original name

        if($request->hasFile('file')){
            $model->addMedia($request->file('file'));
        }
//vendor/spatie/laravel-medialibrary/src/HasMediaTrait.php:53
$media->name = pathinfo($file, PATHINFO_FILENAME);

So i've got "phpCYQ7ed" (temporary php filename) instead of original uploaded file name.
Or maybe i should to store uploaded file separately before attach it to my model?
Don't u think it'll be better to integrate upload file moving-renaming in your package also?

deleteMedia not image files

old verison $model->removeMedia($id); database record and image files removed

new version $model->deleteMedia($id); database record removed but not image files

What could be the problem ?

Pagination

Hey Guys,

I was wondering if there is a way to handle pagination.

I would like to use this library to create something like the WordPress media library, but I do not want to possibly retrieve hundreds of files at once.

Any plans to include something for this? Or is there a easy way to achieve pagination?

Thanks in advance!

Manipulation methods not being applied correctly when chained

Image manipulations don't seem to get correctly applied when convenience methods are chained together. For example, I defined some image manipulations to one of my Eloquent models:

public function registerMediaConversions()
{
    $this->addMediaConversion('small')
        ->setWidth(75)->setHeight(75)->setFit('crop')->setFormat('jpg');

    $this->addMediaConversion('medium')
        ->setWidth(150)->setHeight(150)->setFit('crop')->setFormat('jpg');

    $this->addMediaConversion('large')
        ->setWidth(300)->setHeight(300)->setFit('crop')->setFormat('jpg');

    $this->addMediaConversion('full')
        ->setFormat('jpg');
}

After adding an image via the addMedia() method, I noticed that the package was not obeying the setWidth() and setFit() constraints. This is the image I was testing with.

What I would expect is for the small conversion's image to be 75x75 and cropped to fit inside those dimensions. What actually gets saved is a 176x75 image: http://i.imgur.com/qWxS58Y.jpg

The good news is that the setManipulations() method doesn't have this problem. If I change the small conversion's code to this:

$this->addMediaConversion('small')
    ->setManipulations(['w' => 75, 'h' => 75, 'fit' => 'crop', 'format' => 'jpg']);

Then the image gets correctly cropped to 75x75: http://i.imgur.com/ANr0O9U.jpg

This seems like a bug to me as from looking at the Spatie\MediaLibrary\Conversion\Conversion class it seems like the setX() methods should be able to be chained together.

P.S. Thank you for the package, it's making my life much easier ๐Ÿ‘

Conflicting with spatie/laravel-paginateroute

Your requirements could not be resolved to an installable set of packages.

Problem 1
- Can only install one of: spatie/string[2.0.0, 1.9.1].
- Can only install one of: spatie/string[2.0.0, 1.9.1].
- Can only install one of: spatie/string[2.0.0, 1.9.1].
- spatie/laravel-medialibrary dev-master requires spatie/string ^2.0 -> satisfiable by spatie/string[2.0.0].
- Installation request for spatie/laravel-medialibrary dev-master -> satisfiable by spatie/laravel-medialibrary[dev-master].
- Installation request for spatie/string == 1.9.1.0 -> satisfiable by spatie/string[1.9.1].

Don't create "conversions" directory when there are no conversions

Hi, I think it will be better not to create "conversions" directory when there are no conversions for model, in some cases it creates many empty directories. For example when it's not images uploaded, but documents or videos, or even images but with no conversions. Also makeDirectory($directory.'/conversions'); (or check if it exists) can be moved to performConversions function and launched only if there are any conversions.

Thanks!

Conversions doesn't work.

I think the path to the Conversions interface is wrong and HasMediaTrait doesn't have registerMediaConversions implementation method.

In doc,
...
use Spatie\MediaLibrary\HasMediaConversions;

class News extends Model implements HasMediaConversions
{
use HasMediaTrait;
...
}

Custom fileName/filePath prior toCollectionOnDisk

I've seen it mentioned a few times, but here i am.
I am aware of feature to "rename" $media->file_name, but this is for After the saving on Disk and all the manipulations.

This doesn't work with \Spatie\MediaLibrary\FileAdder\FileAdder objects, that you "actually" get after $model->addMedia($request->file('contents'))

Also, as some ppl noticed: the copyToMediaLibrary does have an optional $subDirectory parameter. However, I haven't found a way(in the docs) to set this parameter anywhere.

Questions are:

  • how to set targetFilename Prior the saveOnDisc?
  • how to set $subDirectory (but this could break compatibility.. as file_name should also be updated)?
  • if media->file_name will have sub-directories(slashes in file_name) will it break anything?

Support: how would you handle different image fields?

Hi,

I have one question when associating medias, how would you handle different image fields?

Let's says my News object needs one "main image", one or many "inline images" and one "facebook image".

Would you use different collections, even if some collection would only have one image, or should i create some table columns containing the media ID?

Thanks for your help!

file name extension

Hi,

First of all, thanks for creating this package.

I have been playing with it and 1 issue so far was that it seem the file extensions are removed (pdf, or png.etc). How do I retain the file extensions as well as some control over the file name?

Thank you.

Update documentation

Please update the documentation in the section 'Basic usage'. I could not get my conversions to work because I used HasMedia instead of HasMediaConversions

namespace App\Models;

use Spatie\MediaLibrary\HasMedia\HasMediaTrait;
use Spatie\MediaLibrary\HasMedia\Interfaces\HasMedia;

class News extends Model implements HasMedia
{
    use HasMediaTrait;
   ...
}

It should be this:

namespace App\Models;

use Spatie\MediaLibrary\HasMedia\HasMediaTrait;
use Spatie\MediaLibrary\HasMedia\Interfaces\HasMediaConversions;

class News extends Model implements HasMediaConversions
{
    use HasMediaTrait;
   ...
}

getFirstMediaURL param incoherence

Hi!

I'm trying to get the first (and only one) media in my collection with getFirstMediaURL() method.

Your documentation says to pass collectionName to this method, or your exemple show getFirstMediaURL('detail') where detail is a profile.

The method doesn't work with profile param, but works with collection name, but original profile is used by default.

Thanks for fix it

[L5.1] Eager loading relationship and calling getMedia()

Firstly, a wonderful, wonderful package. Saved me many hours and I find the quality of code in any Spatie package to be top notch!

I'm using the package in a project where a user can post jobs. The user can of course attach lots of images to jobs using your package.

When I come to display all of a users jobs to them, I do so with a thumbnail of their first image, first by calling a method from my controller to my repository, then sending the data to a view:

// Controller
public function __construct(User $user)
{
    $this->user = $user;
}

public function jobs($username)
{
    $jobs = $this->user->jobs($username);

   return view('user.jobs', compact('jobs'));
}
// Repository
public function __construct(User $user)
{
    $this->user = $user;
}

public function jobs($username)
{
    $user = $this->user->where('username', $username)->first();

    $jobs = $user->jobs;

    return $jobs;
}
// View
@foreach($jobs->chunk(3) as $jobSet)
<div class="row jobs-content-box">
    @foreach ($jobSet as $job)
    <img src="{{ $job->getMedia()[0]->getURL() }}" />
    @endforeach
</div>
@endforeach

This works fine however I am left with rather a lot of queries when I investigate using Laravel's Debugbar.

My question is, is there a way to eager load the getMedia() method rather than having so many queries?

502 Bad Gateway status - Yet files upload and eloquent works

I'm getting a bizarre 502 status code, using Homestead v0.2.7, when I use the following code:

public function store(Request $request, $slug)
    {
        $job = Job::where('slug', $slug)->where('user_id', Auth::id())->first();

        $job->addMedia($request->file('file'))->toCollection('images');
    }

The files are uploaded to the path I specify in 'laravel-medialibrary.php', they work on a local disk and an S3 disk, and the entries appear in the database. So seemingly works perfectly...yet throws a 502!

I should add that it works fine when I use Laravel's traditional
$request->file('photo')->move($destinationPath, $fileName);

Conversions folder not being generated on server?

Hi,

First, thank you for creating this library. It has been really helpful and working well until recently. However, for some reason, the conversions folder is no longer being created on my server. Any thoughts on what might be causing this? The original file is being uploaded properly and calling getFirstMediaUrl('images', 'thumbnail') returns the proper url, but the actual conversions folder and the appropriate file do not exist. As far as I'm aware, no errors are being thrown.

Server permissions on the public folder are 777 and gd is installed.

My model

...
use Spatie\MediaLibrary\HasMedia\Interfaces\HasMediaConversions;
use Spatie\MediaLibrary\HasMedia\HasMediaTrait;

class Listing extends Model implements HasMediaConversions
{

    use HasMediaTrait;

        ...

    public function registerMediaConversions(){
        $this->addMediaConversion('thumbnail')
            ->setManipulations(['w' => 150, 'h' => 170])
            ->performOnCollections('images');
    }
...
}

Add the method where the upload is taking place

        if ( $request->hasFile('thumbnail'))  {
            $listing->addMedia($request->file('thumbnail'))->toCollection('images');
        }

Thanks for your help!

Retrieving a single image from collection

I may just be overlooking something but there doesn't appear to be a simple way to retrieve a single image from a collection, given it's ID (or other identifier), is this the case?

My use case: I have a Product model which has two 'collections', one is a collection containing a single primary product image, and the other contains multiple images used in a gallery/slideshow on the product page. Along with the product details, we have 'Features' section that contains a title, text and image in a carousel format (both for single products and pulling from multiple). Currently the user enters the title, text and selects an image from the collection to use for each 'slide' in the carousel (in which the image ID is stored as the selected img). The problem is, there isn't a simple way to retrieve this image given the ID AND have access to the defined profiles. I thought a simple solution would be querying the media relation with a where clause to match the ID, but since the profiles are hydrated by the repository using a private method there doesn't appear to be a way to grab just a single media object.

Granted we could grab the whole collection and filter it for the id, but it seems a little heavy handed to have to do then when in some cases we only need a single image.

[Suggest] Laravel 4 support

Hi,
i know people are switching to L5 but i think L4 still being used in many project. And with any CMS media management is an important part. So, can you make this package to work with L4 ? Thank you.

spatie/laravel-medialibrary doesn't compatible with spatie/eloquent-sortable ^2.0

Hello... you might want to update spatie/laravel-medialibrary to compatible with spatie/eloquent-sortable update version.

 Problem 1
    - spatie/laravel-medialibrary 3.2.3 requires spatie/eloquent-sortable ^1.1.2 -> no matching package found.
    - spatie/laravel-medialibrary 3.2.2 requires spatie/eloquent-sortable ^1.1.2 -> no matching package found.
    - spatie/laravel-medialibrary 3.2.1 requires spatie/eloquent-sortable ^1.1.2 -> no matching package found.
    - spatie/laravel-medialibrary 3.2.0 requires spatie/eloquent-sortable ^1.1.2 -> no matching package found.
    - Installation request for spatie/laravel-medialibrary ^3.2 -> satisfiable by spatie/laravel-medialibrary[3.2.0, 3.2.1, 3.2.2, 3.2.3]

Special characters and delete the file name space

MediaLibraryRepository.php

private function createMediaForFile($file, $collectionName, $addAsTemporary)
    {
        $pathParts = pathinfo($file);
        $media = new Media();
        $media->name = $pathParts['filename'];

$media->name = str_slug($pathParts['filename']);

It can be an insertion

Profile names with _

It should be noted in the docs that any profile names containing an underscore will not work correctly. We spent a fair bit of time trying to track down why profile images were being created but not being returned when queried, e.g. we have profiles of 'grid', 'grid_sm', 'grid_lg', and only 'grid' would return an image. We thought it was in issue with our app until we looked into the LocalFileSystem class to see the profile names were being parsed by exploding the filenames via underscore.

news / newsitem in readme.md

There are a few examples of this through the readme;

$newsItem = News::find(1);
$news->addMedia($pathToFile);

Should be $newsitem->addmedia ?

Allow direct attribute assignment

Hi

Just a suggestion to take Eloquent integration one step further: how about supporting attribute assignment instead of calling the trait methods?

Instead of doing:

$newsItem->addMedia($pathToFile, $collectionName);

let's do for example:

$newsItem->collectionName($uploadedFile1); // inserts a single file, replaces if exists
$newsItem->collectionName(); // remove all files
$newsItem->collectionName([$uploadedFile2]); // add additional file to existing set
$newsItem->collectionName([$uploadedFile1, $uploadedFile2]); // add multiple files to existing set
// (this is just a quick visualization of how this could look like; more reasoning needs to be done, e.g. handling of empty array etc.)

This would certainly allow for cleaner controller methods since mass assignment will be possible.
For example Stapler has implemented this behavior.

Trait method boot has not been applied

Trait method boot has not been applied, because there are collisions with other trait methods on App\Models\User

use Spatie\MediaLibrary\MediaLibraryModel\MediaLibraryModelInterface;
use Spatie\MediaLibrary\MediaLibraryModel\MediaLibraryModelTrait;

use Zizaco\Entrust\Traits\EntrustUserTrait;
use Laracasts\Presenter\PresentableTrait;

class User extends Model implements AuthenticatableContract, CanResetPasswordContract, MediaLibraryModelInterface {
use Authenticatable, CanResetPassword, PresentableTrait, EntrustUserTrait;
use MediaLibraryModelTrait;

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.