spatie / laravel-medialibrary

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

Call to a member function getMedia() on null in FileAdder.php when try return media collection after upload file for not exists model #3552

Closed pionas closed 7 months ago

pionas commented 9 months ago

Hello,

i have a problem with process media item for new (not exists records).

My function to upload file:

        $model = new Model();
        $model->id = $request->input('model_id', 0);
        $model->exists = true;
        $media = $model->addMediaFromRequest('file')
            ->toMediaCollection(ContentCategory::MEDIA_COLLECTION_NAME);
        $media->wasRecentlyCreated = true;
        return response()->json(compact('media'), Response::HTTP_CREATED);

In my Model in registerMediaCollections and use function onlyKeepLatest(1)

But this throw exception: Error: Call to a member function getMedia() on null in vendor\spatie\laravel-medialibrary\src\MediaCollections\FileAdder.php:473

Problem is for $this->subject->fresh(); beacuse they not found records in database, but when i change my $model->exists for false I have another exception TypeError: Spatie\MediaLibrary\Support\PathGenerator\DefaultPathGenerator::getBasePath(): Return value must be of type string, null returned in vendor\spatie\laravel-medialibrary\src\Support\PathGenerator\DefaultPathGenerator.php:44

When i add

            if (is_null($subject)) {
                $subject = $this->subject;
            }

after this: https://github.com/spatie/laravel-medialibrary/blob/main/src/MediaCollections/FileAdder.php#L473

it works

it is good solution?