🔹 เกริ่นนำ
Laravel มีระบบ Filesystem ที่ยืดหยุ่น ช่วยให้สามารถจัดการไฟล์ได้ทั้งแบบ local, public, และ cloud (เช่น Amazon S3) อย่างง่ายดาย รองรับการอัปโหลดไฟล์จากฟอร์ม, การบันทึกไฟล์, ลบไฟล์ และจัดการ path อย่างปลอดภัยผ่าน Storage facade
บทนี้จะสอนวิธีอัปโหลดไฟล์จากผู้ใช้และจัดเก็บอย่างถูกต้องใน storage โดยใช้ฟีเจอร์ของ Laravel
🔸 ฟอร์มสำหรับอัปโหลด
<form action="/upload" method="POST" enctype="multipart/form-data">
@csrf
<input type="file" name="file">
<button type="submit">อัปโหลด</button>
</form>
🔸 ตัวอย่าง Controller
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
public function upload(Request $request)
{
$request->validate([
'file' => 'required|file|max:2048'
]);
if ($request->hasFile('file')) {
$path = $request->file('file')->store('uploads'); // จัดเก็บใน storage/app/uploads
return response()->json(['path' => $path]);
}
}
🔸 การจัดเก็บแบบ public
$path = $request->file('file')->store('uploads', 'public');
จะเก็บไว้ใน storage/app/public/uploads
และเข้าถึงได้ผ่าน URL /storage/uploads/...
🔸 การสร้าง symbolic link สำหรับ public access
php artisan storage:link
💡 Laravel ใช้
config/filesystems.php
สำหรับกำหนด disk และ root path