Search code examples
file-uploadfilenameslaravel-9

Custom name when upload file in laravel


I wanna ask, how am I supposed to write on the $fileName if I want to custom an image file when I upload it like for example product-code_product-name.jpg or something like 111_instant-noodle.jpg?

and this is the code:

$fileName = <something to code here>;
$path = $request->file('the_file')->storeAs('the_path', $fileName, 'public');
return $path;

or maybe any other way for me to achieve that?

what I want to achieve is when the file is uploaded to the database, I want the file saved with this kind of name "product-code_product-name.jpg" and not use its original name.

I tried:

$fileName = time() . $request->file('the_file')->getClientOriginalName();

but it saved with its original name, and I dont want that, so what am I supposed to do?

thank you for answering my question.


Solution

  • You can do something like this to create custom file name according to your choice/requirement.

    // Combine the sanitized product code and product name
    $customFileName = $productCode . "_" . $productName . ".jpg";
    
    // Replace any spaces with underscores
    $customFileName = str_replace(" ", "_", $customFileName);
    
    // Save the file with the custom filename
    $path = $request->file('the_file')->storeAs('the_path', $customFileName, 'public');