Kritim Yantra
Jun 25, 2025
"Users want to upload images, resumes, documents — and your API needs to handle it like a pro!"
Whether you're building a job portal, a photo-sharing app, or a document manager, file uploads are a must-have feature. In Laravel 12, uploading files via an API is simple, secure, and scalable — if done the right way.
In this step-by-step guide, you'll learn how to:
Let’s dive in!
Here’s what happens behind the scenes:
multipart/form-data
requestLet’s build a Document
model to store uploaded files.
php artisan make:model Document -m
Edit the migration file:
Schema::create('documents', function (Blueprint $table) {
$table->id();
$table->string('name'); // original filename
$table->string('path'); // storage path
$table->timestamps();
});
Run the migration:
php artisan migrate
php artisan make:controller API/DocumentController
In DocumentController.php
:
use Illuminate\Http\Request;
use App\Models\Document;
use Illuminate\Support\Facades\Storage;
class DocumentController extends Controller
{
public function store(Request $request)
{
// ✅ Validate the file
$request->validate([
'file' => 'required|file|mimes:jpg,jpeg,png,pdf|max:2048' // 2MB max
]);
// 🧾 Store file in 'uploads' disk
$path = $request->file('file')->store('uploads', 'public');
// 📦 Save info to DB
$document = Document::create([
'name' => $request->file('file')->getClientOriginalName(),
'path' => $path
]);
// ✅ Return success with path
return response()->json([
'message' => 'File uploaded successfully!',
'file_url' => asset('storage/' . $path)
]);
}
}
In routes/api.php
:
use App\Http\Controllers\API\DocumentController;
Route::post('/upload', [DocumentController::class, 'store']);
Set the request type to POST
and URL to:
http://localhost:8000/api/upload
Under Body tab:
file
File
You should receive:
{
"message": "File uploaded successfully!",
"file_url": "http://localhost:8000/storage/uploads/your-file.jpg"
}
To secure uploads for authenticated users:
Route::middleware('auth:sanctum')->post('/upload', [DocumentController::class, 'store']);
Make sure your API uses Laravel Sanctum for auth.
Want to upload multiple files at once?
Update validation and loop through files:
$request->validate([
'files.*' => 'required|file|mimes:jpg,png,pdf|max:2048'
]);
$paths = [];
foreach ($request->file('files') as $file) {
$paths[] = $file->store('uploads', 'public');
}
Make sure the public
disk is linked:
php artisan storage:link
This allows files stored in /storage/app/public
to be publicly accessible via /storage
.
Storage
facade for saving filesNo comments yet. Be the first to comment!
Please log in to post a comment:
Sign in with Google