1. LATAR BELAKANG
Setelah lima hari belajar dan membangun REST API yang lengkap—dengan routing, controller, database, validasi, error handling, API Resource, dan autentikasi menggunakan Sanctum—tiba saatnya untuk membawa aplikasi kita ke tahap yang sesungguhnya: deployment.
API yang kita bangun selama ini hanya berjalan di lingkungan lokal (localhost). Tentunya ini tidak bisa diakses oleh orang lain atau digunakan oleh tim frontend/mobile yang membutuhkan backend yang aktif 24/7. Deployment adalah proses memindahkan aplikasi dari lingkungan pengembangan ke lingkungan production yang dapat diakses publik.
Pada artikel tambahan ini, saya akan mempelajari cara mendeploy REST API Laravel ke Laravel Cloud—platform hosting resmi dari Laravel yang dirancang khusus untuk aplikasi Laravel. Mengapa Laravel Cloud?
- Optimasi untuk Laravel - Konfigurasi otomatis untuk Laravel
- Mudah digunakan - Tidak perlu pusing dengan konfigurasi server
- SSL otomatis - HTTPS untuk keamanan API
- Database terkelola - Tidak perlu setup database manual
- Environment variables - Mudah mengelola konfigurasi production
- Auto-scaling - Menyesuaikan dengan traffic
2. ALAT DAN BAHAN
2.1 Perangkat Lunak
- Laravel 11 - Project API yang sudah selesai (dari artikel 1-5)
- Git - Untuk version control dan push ke repository
- Akun GitHub/GitLab/Bitbucket - Menyimpan repository kode
- Akun Laravel Cloud - Platform deployment (https://cloud.laravel.com)
- Postman/Thunder Client - Untuk testing API setelah deploy
2.2 Perangkat Keras
- Laptop dengan koneksi internet stabil
- Browser untuk mengakses Laravel Cloud dashboard
3. PEMBAHASAN
3.1 Persiapan Sebelum Deployment
Sebelum mendeploy, ada beberapa hal yang perlu kita persiapkan agar API kita siap untuk lingkungan production.
3.1.1 Membersihkan Kode dan Konfigurasi
# Hapus file-file yang tidak diperlukan di production# Contoh: file dump, file temporary, dll# Generate key jika belumphp artisan key:generate# Clear cachephp artisan config:clearphp artisan route:clearphp artisan view:clear
3.1.2 Menyiapkan File .env untuk Production
Buat template file .env.example yang akan digunakan sebagai referensi:
# File: .env.exampleAPP_NAME="Laravel API" APP_ENV=production APP_DEBUG=false APP_URL=https://your-app.laravel.cloud APP_KEY= DB_CONNECTION=mysql DB_HOST= DB_PORT=3306 DB_DATABASE= DB_USERNAME= DB_PASSWORD= SANCTUM_STATEFUL_DOMAINS=your-app.laravel.cloud SESSION_DOMAIN=.laravel.cloud # CORS untuk mengizinkan akses dari frontendCORS_ALLOWED_ORIGINS=https://your-frontend-domain.com
3.1.3 Mengoptimalkan untuk Production
# Optimasi untuk productionphp artisan config:cachephp artisan route:cachephp artisan event:cache# Optimasi autoloader Composercomposer install --optimize-autoloader --no-dev
3.1.4 Menyiapkan File Penting untuk Deployment
Pastikan file-file berikut ada di project:
composer.json (pastikan sudah lengkap):
{"name": "laravel/laravel","type": "project","require": {"php": "^8.1","guzzlehttp/guzzle": "^7.2","laravel/framework": "^10.0","laravel/sanctum": "^3.2","laravel/tinker": "^2.8"},"require-dev": {"laravel/pint": "^1.0","laravel/sail": "^1.18","mockery/mockery": "^1.4.4","nunomaduro/collision": "^7.0","phpunit/phpunit": "^10.0"},"scripts": {"post-autoload-dump": ["Illuminate\\Foundation\\ComposerScripts::postAutoloadDump","@php artisan package:discover --ansi"],"post-root-package-install": ["@php -r \"file_exists('.env') || copy('.env.example', '.env');\""],"post-create-project-cmd": ["@php artisan key:generate --ansi"]}}
3.2 Git dan Repository
3.2.1 Inisialisasi Git
# Inisialisasi git di projectgit init# Buat .gitignore (sudah otomatis dari Laravel)# Pastikan file berikut masuk .gitignore:# /vendor# .env# .idea/# node_modules/# storage/*.key# .phpunit.result.cache# Add semua filegit add .# Commit pertamagit commit -m "Initial commit: Laravel REST API complete"
3.2.2 Push ke GitHub
# Buat repository baru di GitHub (jangan inisialisasi dengan README)# Lalu jalankan:git remote add origin https://github.com/username/nama-repo.gitgit branch -M maingit push -u origin main
3.3 Deployment ke Laravel Cloud
3.3.1 Mendaftar dan Login ke Laravel Cloud
- Buka https://cloud.laravel.com
- Daftar/Login menggunakan akun GitHub/Laravel
- Setelah login, akan masuk ke dashboard
3.3.2 Membuat Project Baru
- Klik tombol "New Project"
- Pilih "Deploy from Git"
- Pilih provider Git (GitHub, GitLab, atau Bitbucket)
- Authorize Laravel Cloud untuk mengakses repository
- Pilih repository yang sudah kita push
3.3.3 Konfigurasi Environment Variables
Setelah memilih repository, kita akan diminta mengisi environment variables:
| Variable | Nilai | Keterangan |
|---|---|---|
APP_NAME | "My Laravel API" | Nama aplikasi |
APP_ENV | production | Environment |
APP_DEBUG | false | Matikan debug di production |
APP_KEY | (akan digenerate otomatis) | Jangan diisi manual |
APP_URL | https://nama-project.laravel.cloud | URL aplikasi |
DB_CONNECTION | mysql | Database connection |
DB_DATABASE | (disediakan platform) | Nama database |
DB_USERNAME | (disediakan platform) | Username database |
DB_PASSWORD | (disediakan platform) | Password database |
Tips: Untuk database, Laravel Cloud biasanya menyediakan database terkelola. Kita bisa memilih "Add database" dan environment variables akan terisi otomatis.
3.3.4 Menambahkan Database
- Di dashboard project, klik tab "Databases"
- Klik "Create Database"
- Pilih tipe database (MySQL)
- Setelah database dibuat, environment variables akan otomatis terisi
3.3.5 Konfigurasi Build Command
Laravel Cloud akan menjalankan perintah build. Pastikan kita mengatur:
# Build commands (default sudah baik)composer install --no-interaction --prefer-dist --optimize-autoloaderphp artisan migrate --forcephp artisan config:cachephp artisan route:cache
3.3.6 Deploy Pertama
- Klik "Deploy" atau "Trigger Deployment"
- Tunggu proses build selesai (5-10 menit)
- Lihat log deployment untuk memastikan tidak ada error
3.4 Post-Deployment Configuration
3.4.1 Menjalankan Migration di Production
Setelah deploy pertama, kita perlu menjalankan migration:
# Bisa melalui terminal di dashboard Laravel Cloudphp artisan migrate --force
Atau jalankan seeder jika perlu:
php artisan db:seed --force3.4.2 Konfigurasi CORS
Agar API bisa diakses dari frontend (React, Vue, atau mobile app), konfigurasi CORS di file config/cors.php:
<?php// File: config/cors.phpreturn ['paths' => ['api/*', 'sanctum/csrf-cookie'],'allowed_methods' => ['*'],'allowed_origins' => ['https://frontend-domain.com','http://localhost:3000', // untuk development'https://mobile-app.com'],'allowed_origins_patterns' => [],'allowed_headers' => ['*'],'exposed_headers' => [],'max_age' => 0,'supports_credentials' => true,];
Setelah mengubah, deploy ulang aplikasi.
3.4.3 Konfigurasi Sanctum untuk Production
Jika menggunakan Sanctum untuk autentikasi, pastikan konfigurasi sudah benar:
// File: config/sanctum.php'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf('%s%s','localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1',env('APP_URL') ? ','.parse_url(env('APP_URL'), PHP_URL_HOST) : ''))),
Di .env production:
SANCTUM_STATEFUL_DOMAINS=your-app.laravel.cloud,frontend-domain.comSESSION_DOMAIN=.laravel.cloud
3.5 Testing API yang Sudah di Deploy
Setelah deploy berhasil, kita akan mendapatkan URL seperti:
https://nama-project.laravel.cloudSekarang API kita bisa diakses publik. Mari kita test beberapa endpoint:
3.5.1 Test Endpoint Publik
Request:
GET https://nama-project.laravel.cloud/api/postsResponse (200):
{"success": true,"message": "Daftar post berhasil diambil","data": [...],"meta": {"current_page": 1,"last_page": 5,"total": 50}}
3.5.2 Test Register
Request:
POST https://nama-project.laravel.cloud/api/auth/registerContent-Type: application/json{ "name": "User Baru", "email": "user@example.com", "password": "password123", "password_confirmation": "password123"}
Response (201):
{"success": true,"message": "Registrasi berhasil","data": {"user": {...},"token": "1|a1b2c3d4e5f6g7h8i9j0..."}}
3.5.3 Test Login
Request:
POST https://nama-project.laravel.cloud/api/auth/loginContent-Type: application/json{ "email": "user@example.com", "password": "password123"}
Response (200):
{"success": true,"message": "Login berhasil","data": {"user": {...},"token": "2|k1l2m3n4o5p6q7r8s9t0..."}}
3.5.4 Test Protected Endpoint
Request:
POST https://nama-project.laravel.cloud/api/postsAuthorization: Bearer 2|k1l2m3n4o5p6q7r8s9t0...Content-Type: application/json{ "title": "Post dari Production", "content": "Ini adalah post yang dibuat di server production", "category_id": 1}
Response (201):
{"success": true,"message": "Post berhasil dibuat","data": {"id": 51,"title": "Post dari Production","content": "Ini adalah post yang dibuat di server production","user_id": 1,"created_at": "2026-02-28T10:30:00Z"}}
3.6 Mengelola Deployment
3.6.1 Deployment Selanjutnya
Setiap kali kita melakukan perubahan pada kode dan push ke repository:
git add .git commit -m "Fix bug di API posts"git push origin main
Laravel Cloud akan otomatis mendeteksi perubahan dan melakukan deploy ulang (jika diatur auto-deploy).
3.6.2 Melihat Log dan Monitoring
Di dashboard Laravel Cloud, kita bisa melihat:
- Deployment Logs - Riwayat dan status setiap deployment
- Application Logs - Log aplikasi (error, info, dll)
- Metrics - CPU usage, memory, request count
- Database Metrics - Kinerja database
3.6.3 Rollback Jika Terjadi Masalah
Jika deployment baru menyebabkan error, kita bisa rollback ke versi sebelumnya:
- Buka tab "Deployments"
- Cari deployment yang stabil
- Klik "Rollback to this deployment"
3.7 Menambahkan Custom Domain
Laravel Cloud menyediakan domain *.laravel.cloud secara default. Jika ingin menggunakan domain sendiri:
- Buka tab "Domains"
- Klik "Add Domain"
- Masukkan domain (contoh:
api.namaproject.com) - Ikuti petunjuk untuk mengatur DNS (biasanya menambah CNAME record)
- Tunggu propagasi DNS (bisa 1-24 jam)
- SSL certificate akan otomatis terpasang
3.8 Environment-Specific Configuration
3.8.1 Membedakan Konfigurasi Lokal dan Production
Kita bisa memiliki file konfigurasi berbeda untuk environment berbeda:
// File: config/app.php'name' => env('APP_NAME', 'Laravel'),'env' => env('APP_ENV', 'production'),'debug' => (bool) env('APP_DEBUG', false),'url' => env('APP_URL', 'http://localhost'),
Di .env lokal:
APP_ENV=localAPP_DEBUG=trueAPP_URL=http://localhost:8000
Di Laravel Cloud (environment variables):
APP_ENV=productionAPP_DEBUG=falseAPP_URL=https://api.namaproject.com
3.8.2 Menggunakan Fitur Feature Flags
Untuk mengaktifkan/menonaktifkan fitur di production:
// config/features.phpreturn ['social_login' => env('FEATURE_SOCIAL_LOGIN', false),'file_upload' => env('FEATURE_FILE_UPLOAD', true),'comments' => env('FEATURE_COMMENTS', true)];// Di controllerif (config('features.comments')) {// Tampilkan fitur komentar}
3.9 Optimasi untuk Production
3.9.1 Caching
Pastikan semua cache sudah dijalankan:
# Jalankan di server setelah deployphp artisan config:cachephp artisan route:cachephp artisan view:cachephp artisan event:cache
3.9.2 Queue untuk Tugas Berat
Jika API kita memiliki tugas berat (mengirim email, proses gambar), gunakan queue:
// Contoh: mengirim email setelah registrasidispatch(new SendWelcomeEmail($user));
Konfigurasi queue di production:
QUEUE_CONNECTION=database3.9.3 Rate Limiting
Batasi jumlah request untuk mencegah abuse:
// File: app/Http/Kernel.phpprotected $middlewareGroups = ['api' => ['throttle:60,1', // 60 request per menit\Illuminate\Routing\Middleware\SubstituteBindings::class,],];// Atau per endpointRoute::middleware('throttle:10,1')->group(function () {Route::post('/posts', [PostController::class, 'store']);});
3.10 Keamanan di Production
3.10.1 HTTPS
Laravel Cloud otomatis menyediakan SSL, pastikan semua request diarahkan ke HTTPS:
// File: app/Providers/AppServiceProvider.phppublic function boot(){if (env('APP_ENV') === 'production') {\URL::forceScheme('https');}}
3.10.2 Headers Keamanan
Tambahkan middleware untuk security headers:
php artisan make:middleware SecurityHeaders// app/Http/Middleware/SecurityHeaders.phppublic function handle($request, Closure $next){$response = $next($request);$response->headers->set('X-Frame-Options', 'DENY');$response->headers->set('X-Content-Type-Options', 'nosniff');$response->headers->set('X-XSS-Protection', '1; mode=block');$response->headers->set('Referrer-Policy', 'strict-origin-when-cross-origin');return $response;}
Daftarkan di Kernel:
protected $middleware = [// ...\App\Http\Middleware\SecurityHeaders::class,];
3.10.3 Environment Variables Sensitif
Pastikan tidak menyimpan data sensitif di kode:
- Jangan hardcode API keys di controller
- Jangan commit file .env ke Git
- Simpan semua rahasia di environment variables Laravel Cloud
3.11 Monitoring dan Alert
3.11.1 Setup Monitoring
Laravel Cloud menyediakan monitoring dasar. Untuk monitoring lebih lanjut, bisa integrasi dengan:
- Laravel Pulse - Monitoring untuk Laravel
- Sentry - Error tracking
- New Relic - Application performance monitoring
3.11.2 Setup Alert
Atur notifikasi jika terjadi masalah:
- Email alert jika 5xx errors meningkat
- Slack/Discord notification untuk deployment
- SMS untuk critical issues
3.12 Dokumentasi API di Production
Jangan lupa untuk menyediakan dokumentasi API:
Menggunakan Scribe (paket populer):
composer require --dev knuckleswtf/scribephp artisan scribe:generate
Hasilnya akan ada di public/docs dan bisa diakses di:
https://api.namaproject.com/docs3.13 Kendala dan Solusi saat Deployment
| Kendala | Solusi |
|---|---|
| APP_KEY tidak ada | Generate key: php artisan key:generate lalu set di environment variables |
| Migration error | Cek koneksi database, pastikan database sudah dibuat |
| CORS error | Konfigurasi CORS dengan benar, tambahkan domain frontend |
| 404 not found | Pastikan route sudah di-cache, cek file .htaccess atau Nginx config |
| 500 server error | Cek log di dashboard, aktifkan debug sementara untuk tracing |
| Token Sanctum tidak valid | Pastikan SANCTUM_STATEFUL_DOMAINS sudah benar |
| File upload gagal | Cek permission folder storage, set FILESYSTEM_DISK=public |
| Memory limit | Upgrade plan atau optimasi query dan kode |
4. KESIMPULAN
Deployment adalah tahap akhir yang mengubah API lokal menjadi produk nyata yang bisa digunakan oleh banyak orang. Dengan Laravel Cloud, proses deployment menjadi sangat mudah dan terstruktur:
Tahapan Deployment yang Sudah Dilakukan:
- Persiapan
- Membersihkan kode
- Mengoptimalkan untuk production
- Menyiapkan environment variables
Version Control
- Inisialisasi Git
- Push ke repository GitHub
Deployment ke Laravel Cloud
- Membuat project
- Konfigurasi database
- Set environment variables
- Menjalankan deployment
Post-Deployment
- Testing endpoint
- Konfigurasi CORS
- Setup custom domain
- Monitoring dan alert
- API bisa diakses publik 24/7
- HTTPS untuk keamanan data
- Database terkelola (backup otomatis)
- Skalabilitas (menyesuaikan traffic)
- Monitoring dan logging terpusat
- Mudah rollback jika terjadi masalah
Sekarang API Laravel kita sudah hidup di cloud dan siap digunakan oleh:
- Frontend developer (React, Vue, Angular)
- Mobile developer (Android, iOS, Flutter)
- Third-party applications
- Integrasi dengan layanan lain
5. DAFTAR PUSTAKA
- Laravel Official Documentation. (n.d.). Laravel 12.x Documentation - Deployment. https://laravel.com/docs/12.x/deployment
- Laravel Cloud Official Documentation. (n.d.). Getting Started with Laravel Cloud. https://cloud.laravel.com/docs/intro
- Laravel Official Documentation. (n.d.). Laravel 12.x Documentation - Configuration Caching. https://laravel.com/docs/12.x/configuration#configuration-caching
- Laravel Official Documentation. (n.d.). Laravel 12.x Documentation - Environment Configuration. https://laravel.com/docs/12.x/configuration#environment-configuration

0 Komentar