Laravel: File uploading using Storage in a simple way

First let’s configure our storage information, here we are going to use spaces of Digital Ocean.

'spaces' => [
            'driver' => 's3',
            'key'    => env('DIGITAL_OCEAN_KEY'),
            'secret' => env('DIGITAL_OCEAN_SECRET_ACCESS_KEY'),
            'region' => 'nyc3',
            'endpoint' => 'https://nyc3.digitaloceanspaces.com',
            'bucket' => env('DIGITAL_OCEAN_BUCKET'),
            'visibility' => 'public',
        ],

Now, let’s upload our file from a request:

$fileName = Storage::disk('spaces')->put($filePath, request()->file('file'));

With disk() method we select which storage we are going to use, after successfully upload, we get the file name and be able to save in our database.

We can get the final url of this file using:

$fileUrl = Storage::disk('spaces')->url($fileName);

This is going to return the url of this file in Digital Ocean spaces.

Deixe uma resposta

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *