Isak Berglind

Isak Berglind

Change uploaded filenames in the trix editor in nova

Isak Berglind • October 4, 2020

php laravel nova tips

Last week I noticed that some of our image that got uploaded from the trix editor in Nova to S3 was containing non url-safe characters. No big deal i thought, there must be an easy way to 'sluggify' the image names before sending them of to S3. After first reading the Nova docs, and then source diving the nova itself, I found no obvious method of how to do this.

I found, however, Two intresting methods "attach" and "detach", which sounded useful. After a bit of tinkering, I came up with a solution that worked.

The method "attach" gets an instance of the request object as a parameter, and expects an url as the return value.

This is what i came up with:

public function fields(Request $request)
{
    return [
        Trix::make('cms')->attach(function (NovaRequest $request) {
            // Separate file name and extension. The uploaded file is always called 'attachment'.
            [$name, $extension] = explode('.', $request->file('attachment')->getClientOriginalName());

            // Use laravel's own slug function.
            $sluggifiedFileName = Str::slug($name) . '.' . $extension;

            // Store the file in S3. Here I'm saving it to the root folder, but can ofc be saved anywhere.
            $request->file('attachment')->storeAs('/', $sluggifiedFileName, ['disk' => 's3']);

            // Return the url for the newly saved file. Change the
            return 'https://example.com/' . $sluggifiedFileName;
        }),
        // more fields..
    ];
}

If you have more than one trix field, you might want to extract the closure to it's own method. I put it on the parent "Resource" class, like the following:

public function saveAttachment(NovaRequest $request)
{
    // Same as code above.
}

And call it from the trix field like this:

public function fields(Request $request)
{
    return [
        Trix::make('cms_8')->attach([$this, 'saveAttachment']),
        // more fields..
    ];
}

And that's all! No more ugly file names :)

There are some more things to think about however, there is no handling of cases where the file already exists, removal of previously attached files etc. Thats a bit out of scope for this article, but if you need help implementing it, just shoot me an email :)

Did you like this article? Then please let me know on twitter