Laravel - creating custom name on image upload using store
I am trying to upload a file using laravel Storage ie
$request->file('input_field_name')->store('directory_name');
but it stores the file in the specified directory with a random string name.
Now I want to save the uploaded file with a custom name . The current time stamp is concatenated with the actual file name. Is there any quickest and easiest way to achieve this functionality.
+3
source to share
5 answers
You can use the code below:
Use file facade
use Illuminate\Http\File;
Make the following changes to your code
$custom_file_name = time().'-'.$request->file('input_field_name')->getClientOriginalName();
$path = $request->file('input_field_name')->storeAs('directory_name',$custom_file_name);
More: Laravel Filesystem and storeAs as @Alexey Mezenin Mention
Hope this code helps :)
+3
source to share
You can also try this.
$originalName = time().'.'.$file->getClientOriginalName();
$filename = str_slug(pathinfo($originalName, PATHINFO_FILENAME), "-");
$extension = pathinfo($originalName, PATHINFO_EXTENSION);
$path = public_path('/uploads/');
//Call getNewFileName function
$finalFullName = $this->getNewFileName($filename, $extension, $path);
// Function getNewFileName
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;
}
+1
source to share