DEV Community

Charley Kevin
Charley Kevin

Posted on

2

Laravel Upload de Arquivos: Salvar arquivo no Storage

Existem algumas opções para salvar o arquivo no storage e o caminho da pasta no banco de dados. Nesse tutorial irei demostrar salvando apenas o nome do arquivo e criando um armazenamento separado a qual considero a forma mais prática e flexível.


Antes de iniciar você deve saber qual tabela deseja salvar o caminho da imagem e cria-la. No nosso caso iremos salva o avatar do usuário, assim adicionei a coluna avatar no Model User.

Configurações iniciais realizadas iremos criar um espaço novo no storage.

config/filesystems.php:

return [

    // ...

    'disks' => [

        // ...

        'avatars' => [
            'driver' => 'local',
            'root' => storage_path('app/public/avatars'),
            'url' => env('APP_URL').'/storage/avatars',
            'visibility' => 'public',
            'throw' => false,
        ],

    ],

    // ...

];
Enter fullscreen mode Exit fullscreen mode

Assim, quando for salvar o arquivo faça da seguinte forma

app/Http/Controllers/Auth/RegisteredUserController.php:

class RegisteredUserController extends Controller
{
    // ...

    public function store(Request $request): RedirectResponse
    {
        $request->validate([
            'name'     => ['required', 'string', 'max:255'],
            'email'    => ['required', 'string', 'email',
                          'max:255', 'unique:'.User::class],
            'password' => ['required', 'confirmed',
                           Rules\Password::defaults()],
            'avatar'   => ['nullable', 'image'],
        ]);

        if ($request->hasFile('avatar')) { 
            $avatar = $request->file('avatar')
                              ->store(options: 'avatars');
        } 

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
            'avatar' => $avatar ?? null, 
        ]);

        // ...
    }
}
Enter fullscreen mode Exit fullscreen mode

No arquivo Blade use o método abaixo.

<img src="{{ Storage::disk('avatars')->url(Auth::user()->avatar) }}" 
     alt="{{ Auth::user()->name }}"
/>
Enter fullscreen mode Exit fullscreen mode

E caso mude a hospedagem das imagens para um S3, por exemplo. Seria muito prático essa mudança, mudando apenas o disk que salva e mostra o arquivo.

<img src="{{ Storage::disk('s3')->temporaryUrl(Auth::user()->avatar, now()->addMinutes(5)) }}"
     alt="{{ Auth::user()->name }}"
/>
Enter fullscreen mode Exit fullscreen mode

Fonte: https://laraveldaily.com/post/laravel-file-uploads-save-filename-database-folder-url?utm_content=buffer014d6&utm_medium=social&utm_source=linkedin.com&utm_campaign=buffer

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

The best way to debug slow web pages cover image

The best way to debug slow web pages

Tools like Page Speed Insights and Google Lighthouse are great for providing advice for front end performance issues. But what these tools can’t do, is evaluate performance across your entire stack of distributed services and applications.

Watch video

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay