Laravel 8 image upload: Best practices for storing and editing image files?

I need assistance to more understand the concept so I can become a better developer. I want to learn how to refactor the code and erase all duplications.

What’s the best practices for image uploads? Renaming them correctly?

I have a block of code that handles two attachments: LFImage & handoverStatement

    if( $request->hasFile('LFImage') ) {
                $destination = public_path('app/lostFound/lostItems' . $lostFound->LFImage);
                if( File::exists($destination) )
                {
                    File::delete($destination);
                }
                $file = $request->file('LFImage');
                $extension = $file->getClientOriginalExtension();
                $filename = $lostFound->LFNumber . '-' . $lostFound->lostItem . '.' . $extension;
                $file->move('app/lostFound/lostItems', $filename);
                $lostFound->LFImage = $filename;
    
            }
            if( $request->hasFile('handoverStatement') ) {
                $destination = public_path('app/lostFound/handoverStatements' . $lostFound->handoverStatement);
                if( File::exists($destination) )
                {
                    File::delete($destination);
                }
                $file = $request->file('handoverStatement');
                $extension = $file->getClientOriginalExtension();
                $filename = $lostFound->lostItem . '-' . $lostFound->LFNumber . '.' . $extension;
                $file->move('app/lostFound/handoverStatements', $filename);
                $lostFound->handoverStatement = $filename;
            }

They’re exactly the same except with the upload directory.
How can I make it as a one code block across the entire application with changeable file name and location depending on the form?

Some file names require random strings, how can I “Edit” the random string to the file that was uploaded?

I don’t know anything about Laravel, but you could cut the code down by making a function with the parts that change being passed into it.

Not sure what you mean by this, can you explain in a bit more detail?

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.