Abdulrahman Mushref
Abdulrahman Mushref

Reputation: 1005

Laravel 8 - What's the best practices dealing with duplicated code?

In laravel controller there're 5 image uploads, all of them are uploaded to the same directory with the same file renaming except the first string:

if( $request->hasfile('vehicleImageRight') )
        {
            if( File::exists($uploadsDir) )
            {
                File::delete($uploadsDir);
            }
            $file = $request->file('vehicleImageRight');
            $extension = $file->getClientOriginalExtension();
            $filename = 'Right' . '-' . $violation->plateNumber . '-' . $violation->violationType . '.' . $extension;
            $file->move($uploadsDir, $filename);
            $violation->vehicleImageRight = $filename;
        }

In the $filename you can see Right, only that text will be changed to left, front, back

This code is duplicated 5 times which is not good. what's the best practice to have a single code that changes the string based on the file uploaded to its certain input?

Upvotes: 0

Views: 152

Answers (1)

Alvrd Sultan
Alvrd Sultan

Reputation: 11

Create Trait or Helper, use wherever you want and pass changed string into method with parameter.

for example:

Trait

trait FileUploader{
  
public function upload($file, $uploadsDir, $position, $violation)
{
   if( File::exists($uploadsDir) )
   {
     File::delete($uploadsDir);
   }

   $extension = $file->getClientOriginalExtension();
   $filename = $position . '-' . $violation->plateNumber . '-' . $violation->violationType . '.' . $extension;
   $file->move($uploadsDir, $filename);
     
   return $filename;
}

Controller method

class PortfolioController extends Controller {
   use FileUploader;

   public function store(Request $request)
   {
     if( $request->hasfile('vehicleImageRight') )
     {
        $violation->vehicleImageRight = $this->upload('your_file', 'your_upload_dir', 'your_position', 'your_violation');
     }
   }
}

Upvotes: 1

Related Questions