file-uploadfilenameslaravel-9

Custom name when upload file in laravel


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 don't want that, so what am I supposed to do?


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');