Laravel-medialibrary: Easy way to "move" a Media file between models?

Created on 25 Feb 2018  路  2Comments  路  Source: spatie/laravel-medialibrary

Say I add an image to a Post:

$post = Post::find(1);
$image = $post
    ->addMedia($pathToFile)
    ->toMediaCollection();

Is there an easy way to move that image to another Post? It's convoluted, but I came up with:

$post2 = Post::find(2);
$image2 = $post2
    ->addMedia($image->getPath())
    ->toMediaCollection();

The issue here is that any conversions will need to be run again on the second image. Plus, now both posts have a copy of the image (so you'll need to delete it from the first post, if you really wanted to "move" it instead of duplicating it).

There must be a simpler way, right?

Most helpful comment

Thanks @freekmurze.

Any reason why something like this (for moving) wouldn't work?

// the initial post and image
$post = Post::find(1);
$image = $post
    ->addMedia($pathToFile)
    ->toMediaCollection();

// move the image to another post
$post2 = Post::find(2);
$image->model()->associate($post2);
$image->save();

All 2 comments

v7 will have dedicated copy and move methods for this.

https://github.com/spatie/laravel-medialibrary/blob/dc977e3eee4e21707e021d4e7f356ae41c4429af/src/Models/Media.php#L330-L356

Under the hood they'll do the same as what you are doing now.

Just regenerating the files is much easier to do codewise, it all just works. Moving files (potentially across filesystems) would be much harder.

Feel free to send a PR to add those move and copy methods to v6. Of course, add tests.

Thanks @freekmurze.

Any reason why something like this (for moving) wouldn't work?

// the initial post and image
$post = Post::find(1);
$image = $post
    ->addMedia($pathToFile)
    ->toMediaCollection();

// move the image to another post
$post2 = Post::find(2);
$image->model()->associate($post2);
$image->save();
Was this page helpful?
0 / 5 - 0 ratings