Laravel: Upload File ke Folder Public

Upload file/image ke folder public di Laravel

Ubah setting di .env

FILESYSTEM_DISK=public

config/filesystems.php

// ...

'public' => [
    'driver' => 'local',
    'root' => public_path('uploads'),
    // 'root' => base_path('../public_html/uploads'),
    'url' => env('APP_URL') . '/uploads',
    'visibility' => 'public',
    'throw' => false,
],
  • File akan di upload ke folder public/uploads
  • Jika di hosting dan lokasi folder public nya ada di public_html sementara app laravel nya terpisah diluar public_html maka gunakan base_path('../public_html/uploads')
  • Jika lokasi folder public nya ada dalam satu folder app laravel maka langsung gunakan public_path('uploads')

Controller

// store
if ($request->hasFile('logo')) {
    $validated['logo'] = $request->file('logo')->store();
}

// update
use Illuminate\Support\Facades\Storage;
// ...
if ($request->hasFile('logo')) {
    // hapus file lama
    if ($pengaturan->logo) {
        Storage::delete($pengaturan->logo);
    }
    $validated['logo'] = $request->file('logo')->store();
}

Blade view

@if ($pengaturan->logo)
    <img src="{{ asset('uploads/' . $pengaturan->logo) }}" width="100px">
@endif