Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel generate a unique ID using Storage::put

I use Laravel Storage::putFile() when I store uploaded files and I like the convenience of it's automatic unique file name and how it takes care of file extension.

Now I want to get a file from a remote server (file_get_contents($url)) and store it like I did for uploaded files, but I don't find any equal method in the docs.

In https://laravel.com/docs/5.5/filesystem#storing-files in the put method, you have to specify the file name.

like image 499
Positivity Avatar asked Sep 22 '17 07:09

Positivity


4 Answers

$filename = uniqid(). '.' .File::extension($file->getClientOriginalName());
//uniqid() is php function to generate uniqid but you can use time() etc.

$path = "Files/Images/"
Storage::disk('local')->put($path.$filename,file_get_contents($file));
like image 81
BugraDayi Avatar answered Oct 19 '22 19:10

BugraDayi


If you have an UploadedFile instance you can also use $file->hashName()

https://laravel.com/api/5.5/Illuminate/Http/UploadedFile.html#method_hashName

https://github.com/laravel/framework/blob/5.5/src/Illuminate/Http/FileHelpers.php#L52

like image 8
Eduardo Stuart Avatar answered Oct 19 '22 17:10

Eduardo Stuart


To be sure the filename is unique and to get the extension of your file url, you can do like this :

$ext = pathinfo($url, PATHINFO_EXTENSION);    
$filename = bcrypt($url).time().'.'.$ext;
like image 1
Thibault Dumas Avatar answered Oct 19 '22 19:10

Thibault Dumas


If anynone is looking for the default Laravel unique filename generator, behind the scenes Laravel uses Str::random(40) to generate a unique filename when you're uploading a new file.

Here is the method store used on UploadedFile instance when you store a new file:

namespace Illuminate\Http;

/**
 * Store the uploaded file on a filesystem disk.
 *
 * @param  string  $path
 * @param  array|string  $options
 * @return string|false
 */
public function store($path, $options = [])
{
    return $this->storeAs($path, $this->hashName(), $this->parseOptions($options));
}

The hashName() method came from the Trait FileHelpers.php

namespace Illuminate\Http;

/**
 * Get a filename for the file.
 *
 * @param  string|null  $path
 * @return string
 */
public function hashName($path = null)
{
    if ($path) {
        $path = rtrim($path, '/').'/';
    }

    $hash = $this->hashName ?: $this->hashName = Str::random(40);

    if ($extension = $this->guessExtension()) {
        $extension = '.'.$extension;
    }

    return $path.$hash.$extension;
}

So if you follow the same logic as Laravel you can basically use Str::random(40) Laravel's helper to generate a unique filename, for more uniqueness you can append the current datetime to the string.

like image 1
João Hamerski Avatar answered Oct 19 '22 18:10

João Hamerski