Laravel : To rename an uploaded file automatically

后端 未结 7 1307
北海茫月
北海茫月 2020-12-11 04:31

I am allowing users to upload any kind of file on my page, but there might be a clash in names of files. So, I want to rename the file automatically, so that anytime any fil

相关标签:
7条回答
  • 2020-12-11 05:08

    Find this tutorial helpful. file uploads 101

    Everything you need to know about file upload is there.

    -- Edit --

    I modified my answer as below after valuable input from @cpburnz and @Moinuddin Quadri. Thanks guys.

    First your storage driver should look like this in /your-app/config/filesystems.php

    'public' => [
        'driver' => 'local',
        'root' => storage_path('app/public'), // hence /your-app/storage/app/public
        'visibility' => 'public',
    ],
    

    You can use other file drivers like s3 but for my example I'm working on local driver.

    In your Controller you do the following.

    $file = request()->file('file'); // Get the file from request
    $yourModel->create([
        'file' => $file->store('my_files', 'public'),
    ]);
    

    Your file get uploaded to /your-app/storage/app/public/my_files/ and you can access the uploaded file like

    asset('storage/'.$yourModel->image)
    

    Make sure you do

    php artisan storage:link
    

    to generate a simlink in your /your-app/public/ that points to /your-app/storage/app/public so you could access your files publicly. More info on filesystem - the public disk.

    By this approach you could persists the same file name as that is uploaded. And the great thing is Laravel generates an unique name for the file so there could be no duplicates.

    To answer the second part of your question that is to show recently uploaded files, as you persist a reference for the file in the database, you could access them by your database record and make it ->orderBy('id', 'DESC');. You could use whatever your logic is and order by descending order.

    0 讨论(0)
提交回复
热议问题