ptvty
ptvty

Reputation: 5664

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.

Upvotes: 24

Views: 31681

Answers (5)

ilyas mohetna
ilyas mohetna

Reputation: 14

Actually there is a better way while using all native methods from Laravel

Like this :

use \Illuminate\Http\File;
use Illuminate\Support\Facades\Storage;

$path = 'your/path';
$store = Storage::putFile('path/of/storage', File($path));

With this way you can get the auto hashName generated from Laravel Storage. I hope this could be helpful to someone else

Upvotes: 0

João
João

Reputation: 761

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.

Upvotes: 4

BugraDayi
BugraDayi

Reputation: 538

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

Upvotes: 24

Thibault Dumas
Thibault Dumas

Reputation: 1070

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;

Upvotes: 1

Related Questions