Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix renaming files with custom model #3707

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

esadewater
Copy link

@esadewater esadewater commented Sep 10, 2024

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.

Fixes renaming of files when using a custom model with a primary key name other than 'id'.
@patinthehat
Copy link
Collaborator

@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
Copy link
Author

esadewater commented Sep 19, 2024

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

Added test media model with custom key name, migration to alter media table with custom key name and test to rename files on a model with custom key name
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants