Question: How can I change name of uploaded file in Laravel 4.
So far I have been doing it like this:

```
$file = Input::file('file'); 
$destinationPath = 'public/downloads/';
if (!file_exists($destinationPath)) {
    mkdir("./".$destinationPath, 0777, true);
}
$filename = $file->getClientOriginalName();

```

But if I have 2 files with the same name I guess it gets rewritten, so I would like to have something like `(2)` added at the end of the second file name or to change the file name completely

Answer: 
The first step is to check if the file exists. If it doesn't, extract the filename and extension with [`pathinfo()`](http://php.net/pathinfo) and then rename it with the following code:

```
$img_name = strtolower(pathinfo($image_name, PATHINFO_FILENAME));
$img_ext =  strtolower(pathinfo($image_name, PATHINFO_EXTENSION));

$filecounter = 1; 

while (file_exists($destinationPath)) {
    $img_duplicate = $img_name . '_' . ++$filecounter . '.'. $img_ext;
    $destinationPath = $destinationPath . $img_duplicate;  
}

```

The loop will continue renaming files as `file_1`, `file_2` etc. as long as the condition `file_exists($destinationPath)` returns true.
I know this question is closed, but this is a way to check if a filename is already taken, so the original file is not overwriten:

(... in the controller: ... )

```
$path = public_path().'\\uploads\\';
$extension = pathinfo($fileName, PATHINFO_EXTENSION);
$original_filename = pathinfo($fileName, PATHINFO_FILENAME);
$new_filename = $this->getNewFileName($original_filename, $extension, $path);
$upload_success = Input::file('file')->move($path, $new_filename);

```

this function get an "unused" filename:

```
public function getNewFileName($filename, $extension, $path){
    $i = 1;
    $new_filename = $filename.'.'.$extension;
    while( File::exists($path.$new_filename) )
        $new_filename = $filename.' ('.$i++.').'.$extension;
    return $new_filename;
}

```