Skip to main content

Deploy Laravel

This guide will help you deploy a Laravel application to Deployxa.

Overview

Laravel is a PHP web framework for building modern web applications. Deployxa provides optimized deployments for Laravel with automatic configuration.

Features:

  • Automatic framework detection
  • PHP 8.1+ support
  • Composer dependency management
  • Artisan command support
  • Database migrations
  • Queue workers
  • Scheduled tasks
  • Storage linking

Prerequisites

  • A Laravel application (version 9 or higher recommended)
  • A GitHub repository with your code
  • A Deployxa account
  • MySQL or PostgreSQL database (optional)

Quick Start

1. Create Your Laravel App

If you don't have a Laravel app yet:

composer create-project laravel/laravel my-laravel-app
cd my-laravel-app

2. Push to GitHub

git init
git add .
git commit -m "Initial commit"
git remote add origin https://github.com/yourusername/my-laravel-app.git
git push -u origin main

3. Deploy to Deployxa

  1. Go to Deployxa Dashboard
  2. Click "New Project"
  3. Select your GitHub repository
  4. Deployxa will automatically detect Laravel
  5. Click "Deploy"

Your app will be live in under 60 seconds!

Configuration

Detected Settings

Deployxa automatically detects these settings:

SettingValue
FrameworkLaravel
Build Commandcomposer install --no-dev --optimize-autoloader
Output Directorypublic
Start Commandphp artisan serve --host=0.0.0.0 --port=8000
Port8000

Custom Configuration

If you need to customize settings:

  1. Go to ProjectSettingsBuild
  2. Modify settings as needed
  3. Save changes

Example Custom Settings:

{
"buildCommand": "composer install --no-dev --optimize-autoloader",
"outputDirectory": "public",
"startCommand": "php artisan serve --host=0.0.0.0 --port=8000"
}

Environment Variables

Adding Environment Variables

  1. Go to ProjectEnvironment
  2. Click "Add Variable"
  3. Enter key and value
  4. Click "Save"

Required Laravel Environment Variables:

APP_NAME=MyApp
APP_ENV=production
APP_KEY=base64:your-app-key-here
APP_DEBUG=false
APP_URL=https://your-app.deployxa.app

LOG_CHANNEL=stack
LOG_LEVEL=error

DB_CONNECTION=mysql
DB_HOST=your-db-host
DB_PORT=3306
DB_DATABASE=your-database
DB_USERNAME=your-username
DB_PASSWORD=your-password

BROADCAST_DRIVER=log
CACHE_DRIVER=file
FILESYSTEM_DISK=local
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120

MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS="hello@example.com"
MAIL_FROM_NAME="${APP_NAME}"

Generating APP_KEY

Generate a new application key:

php artisan key:generate --show

Copy the output and add it to your environment variables.

Database Configuration

Using Managed Database

  1. Go to ProjectSettingsDatabase
  2. Click "Create Database"
  3. Choose database type (MySQL or PostgreSQL)
  4. Configure database settings
  5. Copy connection details to environment variables

Database Migrations

Run migrations automatically on deployment:

Option 1: Post-Deploy Script

Create a deployment script:

#!/bin/bash
php artisan migrate --force
php artisan config:cache
php artisan route:cache
php artisan view:cache

Option 2: Manual Migration

Run migrations via SSH or console:

php artisan migrate --force

Database Seeding

Seed your database after migration:

php artisan db:seed --force

Storage Configuration

Storage Linking

Create the storage symlink:

php artisan storage:link

This command is automatically run by Deployxa during deployment.

File Storage

Local Storage:

Files are stored in /storage/app/public

Access Files:

$url = asset('storage/file.jpg');

Using External Storage

For production, consider using external storage:

Amazon S3:

FILESYSTEM_DISK=s3
AWS_ACCESS_KEY_ID=your-key
AWS_SECRET_ACCESS_KEY=your-secret
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=your-bucket

Queue Workers

Running Queue Workers

For background jobs, you need queue workers:

Option 1: Separate Service

Create a separate project for queue workers:

php artisan queue:work --sleep=3 --tries=3

Option 2: Supervisor

Use Supervisor to manage queue workers (requires custom Docker setup).

Queue Configuration

Update .env:

QUEUE_CONNECTION=database

Create jobs table:

php artisan queue:table
php artisan migrate

Scheduled Tasks

Running Scheduled Tasks

For scheduled tasks, use a cron service or external scheduler:

Option 1: External Cron Service

Use services like:

  • cron-job.org
  • EasyCron
  • AWS EventBridge

Cron Command:

php artisan schedule:run

Option 2: Custom Docker Setup

Add cron to your Dockerfile:

RUN apt-get update && apt-get install -y cron
COPY crontab /etc/cron.d/laravel-cron
RUN chmod 0644 /etc/cron.d/laravel-cron
RUN crontab /etc/cron.d/laravel-cron

Caching

Configuration Cache

Cache your configuration:

php artisan config:cache

Route Cache

Cache your routes:

php artisan route:cache

View Cache

Compile your Blade templates:

php artisan view:cache

Clear Cache

Clear all caches:

php artisan cache:clear
php artisan config:clear
php artisan route:clear
php artisan view:clear

Custom Domains

Adding a Custom Domain

  1. Go to ProjectDomains
  2. Click "Add Domain"
  3. Enter your domain (e.g., example.com)
  4. Configure DNS records
  5. Wait for verification

DNS Configuration

For Apex Domain (example.com):

Type: A
Name: @
Value: 76.76.21.21

For Subdomain (www.example.com):

Type: CNAME
Name: www
Value: cname.deployxa.com

Update APP_URL

Update your APP_URL environment variable:

APP_URL=https://example.com

Performance Optimization

Enable OPcache

OPcache is enabled by default in Deployxa's PHP runtime.

Optimize Autoloader

Optimize Composer autoloader:

composer install --optimize-autoloader --no-dev

This is automatically done by Deployxa.

Use CDN

Serve static assets via CDN:

// config/app.php
'asset_url' => env('ASSET_URL', 'https://cdn.example.com'),

Database Indexing

Add indexes to frequently queried columns:

Schema::table('users', function (Blueprint $table) {
$table->index('email');
});

Monitoring

Viewing Logs

  1. Go to ProjectLogs
  2. Select log type:
    • Build Logs: Deployment process
    • Runtime Logs: Application output
    • Error Logs: Application errors

Laravel Logging

Configure logging in .env:

LOG_CHANNEL=stack
LOG_LEVEL=error

View logs in storage:

storage/logs/laravel.log

Monitoring Metrics

  1. Go to ProjectAnalytics
  2. View metrics:
    • Request count
    • Response times
    • Error rates
    • Bandwidth usage
    • CPU/RAM usage

Health Checks

Deployxa automatically monitors your application:

  • HTTP health checks every 30 seconds
  • Automatic restart on failure
  • Alerts on consecutive failures

Troubleshooting

500 Internal Server Error

Problem: Application returns 500 error

Solution:

  1. Check runtime logs for errors
  2. Verify environment variables
  3. Check database connection
  4. Ensure APP_KEY is set
  5. Check file permissions

Database Connection Failed

Problem: SQLSTATE[HY000] [2002] Connection refused

Solution:

  1. Verify database credentials
  2. Check database host and port
  3. Ensure database exists
  4. Check firewall rules
  5. Verify database user permissions

Migration Failed

Problem: php artisan migrate fails

Solution:

  1. Check database connection
  2. Verify migration files
  3. Check for syntax errors
  4. Run migrations locally first
  5. Check database permissions

Storage Not writable

Problem: The stream or file could not be opened

Solution:

  • Deployxa automatically sets correct permissions
  • If issue persists, check storage directory exists
  • Verify storage and bootstrap/cache directories

Session Not Working

Problem: Sessions not persisting

Solution:

  1. Check SESSION_DRIVER setting
  2. Verify storage permissions
  3. Check session configuration
  4. Ensure APP_KEY is set
  5. Clear session cache: php artisan cache:clear

Queue Jobs Not Processing

Problem: Queue jobs not running

Solution:

  1. Ensure queue worker is running
  2. Check QUEUE_CONNECTION setting
  3. Verify queue table exists
  4. Check queue worker logs
  5. Restart queue worker

Best Practices

Project Structure

my-laravel-app/
├── app/
├── bootstrap/
├── config/
├── database/
├── public/
├── resources/
├── routes/
├── storage/
├── tests/
├── .env.example
├── composer.json
├── artisan
└── README.md

Environment Variables

  • Never commit .env file
  • Use .env.example as template
  • Rotate secrets regularly
  • Use different values per environment

Security

  • Keep Laravel updated
  • Use HTTPS only
  • Validate all inputs
  • Use CSRF protection
  • Sanitize user data
  • Use parameterized queries

Performance

  • Use caching (config, route, view)
  • Optimize database queries
  • Use queue for background jobs
  • Enable OPcache
  • Use CDN for static assets
  • Minimize HTTP requests

Database

  • Use migrations for schema changes
  • Index frequently queried columns
  • Use transactions for complex operations
  • Backup database regularly
  • Use connection pooling

Advanced Configuration

Custom PHP Configuration

Create php.ini:

upload_max_filesize = 64M
post_max_size = 64M
memory_limit = 256M
max_execution_time = 60

Custom Nginx Configuration

For advanced routing, create custom Nginx config:

server {
listen 8000;
root /app/public;

location / {
try_files $uri $uri/ /index.php?$query_string;
}

location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}

Multi-Environment Setup

Use different environment variables per environment:

# Production
APP_ENV=production
APP_DEBUG=false

# Staging
APP_ENV=staging
APP_DEBUG=true

# Development
APP_ENV=local
APP_DEBUG=true

Examples

Basic Laravel App

// routes/web.php
Route::get('/', function () {
return view('welcome');
});

API Endpoint

// routes/api.php
Route::get('/users', function () {
return User::all();
});

Database Model

// app/Models/User.php
class User extends Model
{
protected $fillable = ['name', 'email', 'password'];
}

Migration

// database/migrations/xxxx_create_users_table.php
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});

Resources


Need Help? Contact support@deployxa.com or join our community Discord.