spatie / laravel-medialibrary

Associate files with Eloquent models
https://spatie.be/docs/laravel-medialibrary
MIT License
5.78k stars 1.08k forks source link

Fix renaming files with custom model #3707

Closed esadewater closed 1 week ago

esadewater commented 2 months ago

This PR attempts to fix file renaming when using a custom model with a primary key name other than 'id'.

We use a custom model that changes the primary key name from id to media_id:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Spatie\MediaLibrary\MediaCollections\Models\Media as BaseMedia;

class Media extends BaseMedia
{
    use HasUuids;

    protected $primaryKey = 'media_id';
}

We want to rename a file as described in the docs (Retrieving media):

$mediaItems[0]->file_name = 'newFileName.jpg';
$mediaItems[0]->save();

When renaming file src/MediaCollections/Filesystem.php tries to find a media model using the id attribute instead of the actual primary key. This PR fixes this bug by using ->getKey() in this specific place, which works in both cases.

patinthehat commented 2 months ago

@esadewater would you mind adding a unit test that makes sure both id and a custom id value continue to work as expected? Thanks!

esadewater commented 2 months ago

@patinthehat Sure, I've added a unit test for a media model with a custom key name.

timvandijck commented 1 week ago

Thanks for the PR!