skip to Main Content

in the nova resource I can define an image field with a media library addon package like:

Images::make('Main image', 'media_main')
    ->setFileName(static function($originalFilename, $extension) {
         return md5($originalFilename) . '.' . $extension;
}),

How can I use a function from the resource so that I can use the function multiple times for more Images fields and don’t use duplicate code always for the same functionality.

For example:

public static function fileName($originalFilename, $extension) {
    return md5($originalFilename) . '.' . $extension;
}

So that in the fields section I can use multiple times:

Images::make('Main image', 'media_main')
    ->setFileName(self::fileName($originalFilename, $extension)),

The last call always results in an error message, because I can not grab the parameters. What I’m doing wrong? I think I have a misconception …

2

Answers


  1. Chosen as BEST ANSWER

    This solution works. Is it the best solution?

    ->setFileName(fn($originalFilename, $extension) => self::fileName($originalFilename, $extension)),
    

  2. The error you are getting, is because you are calling the function, not passing a Closure/callable as an argument.

    ->setFileName(self::fileName($originalFilename, $extension)) is calling the static fileName function, not passing the function/Closure itself.

    Here are a couple alternatives:

    class Resource extends LaravelNovaResource
    {
        ...
        protected function filenameFormater()
        {
             return function ($originalFilename, $extension) {
                  return md5($originalFilename) . '.' . $extension;
             };
        }
        ...
    }
    
    class SomeResource extends Resource
    {
        ...
    
        public function fields()
        {
            return [
                ...
                Images::make('Main image', 'media_main')
                     ->setFileName($this->filenameFormatter()),
                ...
            ];
        }
    
    }
    

    Or:

    class SomeResource extends Resource
    {
        ...
    
        public function fields()
        {
            $formatter = function ($originalFilename, $extension) {
                return md5($originalFilename) . '.' . $extension;
            };
    
            return [
                ...
                Images::make('Main image', 'media_main')
                     ->setFileName($formatter),
                ...
            ];
        }
    
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search