Uploading files lets users send pictures, documents, or other data to your website. It helps you save and use these files later.
Uploading files in Laravel
<?php
// In your controller method
public function upload(Request $request)
{
$request->validate([
'file' => 'required|file|max:10240', // max 10MB
]);
$path = $request->file('file')->store('uploads');
return back()->with('success', 'File uploaded to ' . $path);
}Use store() to save files in the default storage folder.
Validate files to check size and type before saving.
<?php // Store file in 'uploads' folder with original name $path = $request->file('file')->storeAs('uploads', $request->file('file')->getClientOriginalName());
<?php // Store file publicly accessible $path = $request->file('file')->store('uploads', 'public');
<?php // Validate file type and size $request->validate([ 'file' => 'required|mimes:jpg,png,pdf|max:5120', ]);
This example shows a simple Laravel controller with two methods: one to display the upload form and one to handle the file upload. The form uses enctype="multipart/form-data" to send files. The controller validates the file and stores it in the 'uploads' folder. After uploading, it shows a success message with the file path.
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class FileUploadController extends Controller { public function showForm() { return view('upload-form'); } public function upload(Request $request) { $request->validate([ 'file' => 'required|file|max:2048', // max 2MB ]); $path = $request->file('file')->store('uploads'); return back()->with('success', "File uploaded to: $path"); } } // Blade view: resources/views/upload-form.blade.php // // <form method="POST" action="{{ route('file.upload') }}" enctype="multipart/form-data"> // @csrf // <input type="file" name="file" aria-label="Choose file to upload" required> // <button type="submit">Upload</button> // </form> // // @if(session('success')) // <p>{{ session('success') }}</p> // @endif
Always use enctype="multipart/form-data" in your HTML form to allow file uploads.
Use Laravel's validation to protect your app from unwanted file types or large files.
Files are stored in the storage/app folder by default. Use php artisan storage:link to make files accessible publicly.
Uploading files lets users send data to your app.
Use Laravel's store() method to save files easily.
Always validate files and set proper form encoding.