dinandmentink / nova-markdown

Adds a markdown editor component to laravel nova.
MIT License
36 stars 4 forks source link

Provide resource information with uploads #13

Closed romanzipp closed 3 years ago

romanzipp commented 3 years ago

In an attempt to replace the image storing process (using spatie/laravel-medialibrary), I have overridden the default provided Controller but needed some kind of information to associate the image with a model.

This PR introduces resourceName and resourceId as new parameters to be provided for the upload controller.

This is my custom upload controller:

<?php

namespace App\Http\Nova;

use DinandMentink\Markdown\Http\Requests\UploadStoreRequest;
use Illuminate\Validation\ValidationException;
use Laravel\Nova\Nova;
use Spatie\MediaLibrary\HasMedia;

class MarkdownUploadController
{
    public function __invoke(UploadStoreRequest $request)
    {
        // Locate the nova resource for the given resource name

        /** @var \Laravel\Nova\Resource $resourceClass */
        $resourceClass = Nova::resourceForKey($request->input('resourceName'));

        if (null === $resourceClass || ! class_exists($resourceClass)) {
            throw ValidationException::withMessages(['resourceName' => 'Invalid resource provided']);
        }

        // Retreive the associated model for the resource

        /** @var \Illuminate\Database\Eloquent\Model $model */
        $model = $resourceClass::$model::findOrFail($request->input('resourceId'));

        // Check if the model has implemented the media library interface
        if ( ! $model instanceof HasMedia) {
            throw ValidationException::withMessages(['resourceName' => 'The given resource can not store images']);
        }

        // Store the media
        $media = $model
            ->addMedia($request->file('image'))
            ->toMediaCollection('content');

        return ['url' => $media->getUrl()];
    }
}
dinandmentink commented 3 years ago

Thanks for your PR! I'll have a look, will probably be friday 17th or 24th.

Does this PR aim to be backwards compatible, so could it be released as v2.x?

romanzipp commented 3 years ago

I've updated the validation rules from required to nullable since the props itself are not required. Should be compatible with older versions šŸ‘