DebianDebian Based

How To Install Laravel on Debian 13

Install Laravel on Debian 13

Installing Laravel on Debian 13 provides developers with a modern PHP framework running on a stable, cutting-edge Linux distribution. Laravel’s elegant syntax and powerful features, combined with Debian 13’s latest packages and improved performance, create an ideal development environment for web applications.

This comprehensive guide walks you through every step needed to successfully install and configure Laravel on Debian 13. You’ll learn to set up the complete LAMP stack, install Composer, configure Laravel, and optimize your installation for both development and production environments.

Table of Contents

Prerequisites and System Requirements

Before beginning the Laravel installation process, ensure your Debian 13 system meets the necessary requirements and has proper access privileges configured.

System Specifications

Your Debian 13 server requires minimum hardware specifications to run Laravel effectively. A minimum of 2GB RAM ensures smooth operation during development, while 5GB of available disk space accommodates the Laravel framework, dependencies, and initial project files. These requirements scale based on your application’s complexity and expected traffic volume.

Root or sudo access privileges are essential for installing system packages and configuring web server components. Most installation commands require elevated permissions to modify system files and install software packages.

Required Software Components

Laravel depends on several core components that form the foundation of your development stack. PHP 8.4 or higher represents the latest stable version available in Debian 13 repositories, providing enhanced performance and security features. The web server component requires either Apache2 or Nginx, with Apache2 being the most commonly used option for Laravel installations.

Database functionality necessitates MySQL or MariaDB server installation. MariaDB serves as the default choice due to its open-source nature and full MySQL compatibility. Composer, PHP’s dependency manager, handles Laravel’s extensive package ecosystem and automates framework updates.

Essential PHP extensions include curl for HTTP requests, sqlite3 for database testing, mysql for MariaDB connectivity, mbstring for string handling, xml for XML processing, bcmath for mathematical operations, tokenizer for PHP parsing, and zip for archive handling.

Domain and Network Setup

Development environments can utilize localhost or local IP addresses, while production deployments require valid domain names with proper DNS configuration. Network connectivity enables package downloads and Composer dependency resolution during installation.

Firewall considerations include opening ports 80 (HTTP) and 443 (HTTPS) for web traffic, along with port 22 for SSH access if managing remote servers. Database ports (3306 for MySQL/MariaDB) should remain restricted to localhost unless external database access is specifically required.

Step 1: Update System and Install LAMP Stack

The foundation of any Laravel installation begins with a properly configured LAMP (Linux, Apache, MySQL, PHP) stack. This comprehensive setup ensures all required components work seamlessly together.

System Update Process

Begin by refreshing your package repositories and installing the latest security updates. The command sudo apt update && sudo apt upgrade -y performs both operations efficiently. Repository refresh ensures access to the most current package versions, while system updates patch security vulnerabilities and improve stability.

System updates typically require 5-10 minutes depending on the number of available updates and your internet connection speed. Reboot your system if kernel updates are installed to ensure all changes take effect properly.

Apache2 Web Server Installation

Install Apache2 using the package manager with sudo apt install apache2. This command downloads and configures the web server with default settings suitable for most Laravel applications. Apache2 automatically creates necessary directories and sets appropriate permissions for web content.

Verify Apache installation by checking the service status with systemctl status apache2. A properly configured Apache service shows “active (running)” status with no error messages. Test functionality by accessing http://localhost in your web browser, which should display the default Apache welcome page.

Enable Apache to start automatically at boot time using sudo systemctl enable apache2. This ensures your web server restarts automatically after system reboots, maintaining application availability.

PHP 8.4 Installation with Extensions

Debian 13 repositories include PHP 8.4, the latest stable release offering improved performance and new language features. Install the core PHP package with sudo apt install php8.4.

Laravel requires specific PHP extensions for optimal functionality. Install essential extensions using a single command:

sudo apt install php8.4-curl php8.4-sqlite3 php8.4-mysql php8.4-mbstring php8.4-xml php8.4-bcmath php8.4-tokenizer php8.4-zip

Each extension serves critical functions within Laravel applications. The curl extension handles HTTP requests to external APIs. SQLite3 provides lightweight database functionality for testing. MySQL extension enables MariaDB connectivity. Mbstring processes multibyte character strings essential for international applications.

Verify PHP installation with php -v to confirm version 8.4 is active. List installed modules using php -m to ensure all required extensions are properly loaded.

MariaDB Database Installation

Install MariaDB server using sudo apt install mariadb-server. This command sets up the database server with default configuration suitable for development environments.

Secure your MariaDB installation by running sudo mysql_secure_installation. This interactive script guides you through essential security configurations including setting the root password, removing anonymous users, disabling remote root login, and removing test databases.

Start and enable MariaDB service with sudo systemctl start mariadb and sudo systemctl enable mariadb. Verify proper operation using sudo systemctl status mariadb to confirm the service runs without errors.

Create a dedicated database and user for your Laravel application. Access MariaDB as root with sudo mysql -u root -p and execute the following commands:

CREATE DATABASE laravel_app;
CREATE USER 'laravel_user'@'localhost' IDENTIFIED BY 'secure_password';
GRANT ALL PRIVILEGES ON laravel_app.* TO 'laravel_user'@'localhost';
FLUSH PRIVILEGES;
EXIT;

Step 2: Install and Configure Composer

Composer serves as PHP’s dependency manager, enabling Laravel installation and package management throughout your application’s lifecycle.

Composer Installation Methods

The official installation method provides the most current Composer version with automatic updates. Download and install Composer using the following command sequence:

curl -sS https://getcomposer.org/installer | php
sudo mv composer.phar /usr/local/bin/composer
sudo chmod +x /usr/local/bin/composer

This approach downloads the Composer installer, executes it to create composer.phar, moves the executable to the global binary directory, and sets proper execution permissions.

Global accessibility allows executing Composer from any directory using the composer command. Verify installation success with composer --version, which should display the current Composer version and build information.

Composer Configuration

Configure Composer for optimal performance in your development environment. Increase memory limits for large projects by setting COMPOSER_MEMORY_LIMIT=-1 in your shell profile. This prevents memory exhaustion errors during complex dependency resolution.

Authentication setup may be required for private repositories or when GitHub API rate limits are exceeded. Generate a GitHub personal access token and configure it using composer config -g github-oauth.github.com YOUR_TOKEN.

Alternative Installation via Package Manager

Debian repositories include Composer packages installable via sudo apt install composer. This method provides easier maintenance through standard package updates but may offer older Composer versions.

Package manager installation integrates with system update cycles, automatically updating Composer alongside other system packages. However, development environments often benefit from the latest Composer features available through the official installation method.

Version compatibility considerations include checking Laravel requirements against available Composer versions. Laravel 11 requires Composer 2.0 or higher, which both installation methods satisfy on Debian 13.

Step 3: Install Laravel Framework

Laravel installation through Composer creates a complete project structure with all necessary dependencies and configuration files.

Laravel Installation via Composer

Navigate to your web server’s document root with cd /var/www/html. This directory serves as the default location for Apache virtual hosts and web applications.

Create a new Laravel project using Composer’s create-project command:

composer create-project laravel/laravel my-app

This command downloads Laravel’s latest stable release along with all dependencies. The installation process typically requires 3-5 minutes depending on network speed and system performance.

Project creation generates a complete directory structure including application logic, configuration files, database migrations, and frontend assets. The installer automatically configures basic settings and generates security keys.

Project Structure Overview

Laravel’s organized directory structure promotes maintainable code and clear separation of concerns. The app directory contains your application’s core logic including models, controllers, and middleware. Configuration files reside in the config directory, providing centralized settings management.

The database directory houses migrations, seeders, and factories for database management. Resources including views, language files, and uncompiled assets are stored in the resources directory. Application routes are defined in the routes directory, separating web, API, and console routes.

Important files include .env for environment configuration, composer.json for dependency management, and artisan for command-line operations. Verify Laravel installation by checking the version with php artisan --version.

Alternative Installation Methods

The Laravel installer provides a global command-line tool for creating new projects. Install globally using composer global require laravel/installer, then create projects with laravel new project-name.

Git clone method enables installation from source repositories, useful for contributing to Laravel development or accessing pre-release versions. This approach requires manual dependency installation using composer install.

Specify particular Laravel versions during installation using version constraints: composer create-project laravel/laravel my-app "10.*" installs the latest Laravel 10.x release.

Step 4: Configure File Permissions and Ownership

Proper file permissions ensure security while enabling Laravel’s functionality, particularly for storage and caching operations.

Setting Proper Ownership

Change ownership of Laravel files to the web server user account. Apache runs under the www-data user on Debian systems, requiring ownership alignment for proper file access:

sudo chown -R www-data:www-data /var/www/html/my-app

Ownership configuration enables the web server to read application files and write to specific directories as needed. Incorrect ownership prevents Laravel from functioning properly and generates permission errors.

Security implications include ensuring application files remain protected from unauthorized access while maintaining necessary write permissions for framework operations.

Directory Permissions Configuration

Laravel requires write access to storage and bootstrap cache directories for session management, logging, and compiled views. Set appropriate permissions using:

sudo chmod -R 775 /var/www/html/my-app/storage
sudo chmod -R 775 /var/www/html/my-app/bootstrap/cache

Permission levels follow standard Unix notation where 775 grants read, write, and execute permissions to owner and group, with read and execute permissions for others. This configuration balances functionality with security requirements.

The storage directory contains session files, logs, and uploaded content requiring write access. Bootstrap cache stores compiled configuration and route information for improved performance.

Security Best Practices

Production environments require more restrictive permissions to minimize security risks. File permissions should be 644 for regular files and 755 for directories, with storage and cache directories maintaining 775 permissions.

Avoid using 777 permissions which grant full access to all users, creating significant security vulnerabilities. Regular permission auditing ensures configurations remain secure and functional as applications evolve.

Implement automated permission checks in deployment scripts to maintain consistent security postures across environments.

Step 5: Environment Configuration (.env Setup)

Laravel’s environment configuration system enables flexible settings management across development, staging, and production environments.

Environment File Setup

Copy the example environment file to create your application’s configuration: cp .env.example .env. The .env file contains sensitive configuration data including database credentials, API keys, and application settings.

Environment variables provide isolated configuration for different deployment contexts. Development environments typically enable debugging and use local databases, while production settings prioritize security and performance.

Application Key Generation

Generate a unique application key using Laravel’s Artisan command: php artisan key:generate. This key encrypts session data, password reset tokens, and other sensitive information within your application.

Application keys must be unique across installations to prevent security vulnerabilities. The key generation process creates a cryptographically secure random string and automatically updates your .env file.

Key security considerations include protecting the .env file from unauthorized access and rotating keys periodically in production environments.

Database Configuration

Configure database connection settings in your .env file:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_app
DB_USERNAME=laravel_user
DB_PASSWORD=secure_password

Database connectivity enables Laravel’s Eloquent ORM and migration system. Test connections using php artisan migrate:status to verify proper database access.

Connection parameters include host address, port number, database name, username, and password. Local development typically uses localhost (127.0.0.1), while production environments may specify remote database servers.

Additional Environment Settings

Configure the application URL to match your domain or local development address: APP_URL=http://localhost. This setting affects generated URLs within your application.

Debug mode should be enabled during development (APP_DEBUG=true) to display detailed error information. Production environments must disable debugging (APP_DEBUG=false) to prevent information disclosure.

Mail configuration enables email functionality through various providers including SMTP, Mailgun, and Amazon SES. Cache and session drivers can be configured for Redis, Memcached, or file-based storage depending on your infrastructure requirements.

Step 6: Apache Virtual Host Configuration

Virtual hosts enable multiple websites on a single Apache server, providing isolated configurations for different applications.

Create Apache Virtual Host

Navigate to Apache’s sites directory with cd /etc/apache2/sites-available. Create a new virtual host configuration file named laravel.conf:

<VirtualHost *:80>
    ServerName my-laravel-app.local
    DocumentRoot /var/www/html/my-app/public
    
    <Directory /var/www/html/my-app/public>
        AllowOverride All
        Require all granted
        Options Indexes FollowSymLinks
    </Directory>
    
    ErrorLog ${APACHE_LOG_DIR}/laravel_error.log
    CustomLog ${APACHE_LOG_DIR}/laravel_access.log combined
</VirtualHost>

Document root points to Laravel’s public directory, which contains the index.php file and handles all web requests. The AllowOverride directive enables .htaccess files for URL rewriting.

Directory permissions grant access to web content while maintaining security. Error and access logs provide debugging information and traffic monitoring capabilities.

Enable Virtual Host and Modules

Enable your new virtual host configuration: sudo a2ensite laravel.conf. This command creates a symbolic link in the sites-enabled directory, activating your configuration.

Enable mod_rewrite module for Laravel’s routing system: sudo a2enmod rewrite. URL rewriting transforms friendly URLs into framework-compatible formats, enabling clean route definitions.

Restart Apache to apply configuration changes: sudo systemctl restart apache2. Verify the restart completed successfully using sudo systemctl status apache2.

Disable the default Apache site if not needed: sudo a2dissite 000-default. This prevents conflicts with your Laravel application and improves security.

DNS Configuration

Local development requires hosts file configuration to resolve your chosen domain name. Add the following entry to /etc/hosts:

127.0.0.1    my-laravel-app.local

Production environments require proper DNS records pointing your domain to the server’s IP address. Configure A records for the root domain and any subdomains used by your application.

SSL setup considerations include obtaining certificates from Let’s Encrypt or commercial certificate authorities. HTTPS provides encryption for sensitive data transmission and improves search engine rankings.

Testing Virtual Host Configuration

Verify Apache configuration syntax with sudo apache2ctl configtest. This command identifies syntax errors before applying configurations to prevent service interruptions.

Access log monitoring helps troubleshoot configuration issues and monitor application usage. View recent log entries using sudo tail -f /var/log/apache2/laravel_access.log.

Common troubleshooting steps include checking file permissions, verifying virtual host configuration, and ensuring all required Apache modules are enabled.

Step 7: Database Setup and Migration

Laravel’s migration system provides version control for your database schema, enabling collaborative development and consistent deployments.

Database Creation

Access MariaDB as the root user: sudo mysql -u root -p. Create a dedicated database for your Laravel application with appropriate character set and collation:

CREATE DATABASE laravel_app CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

Character set configuration ensures proper handling of international characters and emoji in your application data. UTF8MB4 provides full Unicode support including 4-byte characters.

Create a dedicated database user with limited privileges following the principle of least access. Grant only necessary permissions to reduce security risks from potential application vulnerabilities.

Laravel Database Configuration

Update your .env file with the database credentials created in the previous step. Ensure connection parameters match your MariaDB configuration exactly to prevent authentication errors.

Test database connectivity using Laravel’s built-in database commands. Run php artisan migrate:status to verify successful connection establishment. This command displays migration status without executing any changes.

Database configuration verification includes checking timezone settings, character encoding, and connection limits to ensure optimal performance.

Run Initial Migrations

Execute Laravel’s default migrations to create essential database tables: php artisan migrate. This command creates tables for users, password resets, failed jobs, and personal access tokens.

Migration system tracks applied changes using a migrations table, preventing duplicate execution and enabling rollback capabilities. Each migration file contains up and down methods for applying and reversing changes.

Verify table creation by accessing your database and listing tables: SHOW TABLES;. Successful migration creates several tables with proper structure and indexes.

Step 8: Testing Laravel Installation

Comprehensive testing ensures your Laravel installation functions correctly and is ready for development activities.

Access Laravel Application

Navigate to your configured domain or IP address in a web browser. Laravel’s welcome page confirms successful installation and displays framework version information along with helpful links to documentation and learning resources.

Install Laravel on Debian 13

The welcome page includes links to Laravel documentation, Laracasts video tutorials, Laravel News, and the GitHub repository. These resources provide excellent starting points for learning Laravel development.

Verify that CSS and JavaScript assets load properly, indicating correct virtual host configuration and file permissions.

Run Laravel Development Server

Laravel includes a built-in development server for quick testing and development. Start the server using php artisan serve, which launches a web server on localhost port 8000.

Development server functionality provides an alternative to Apache virtual hosts during early development phases. Access your application at http://localhost:8000 to verify proper operation.

Development server configuration includes specifying custom ports using --port=8080 or binding to specific IP addresses with --host=192.168.1.100 for network access.

Basic Functionality Tests

Test Laravel’s routing system by creating a simple route in routes/web.php:

Route::get('/test', function () {
    return 'Laravel installation successful!';
});

Route testing verifies URL rewriting and framework initialization. Access /test in your browser to confirm the route responds correctly.

Database connectivity testing includes creating a simple model and performing basic operations. Use php artisan tinker to interact with your application through an interactive shell.

Error handling verification involves accessing non-existent routes to ensure Laravel displays appropriate error pages rather than server errors.

Troubleshooting Common Issues

Understanding common installation problems and their solutions helps maintain a functional Laravel development environment.

Permission-Related Issues

Storage directory permissions represent the most frequent Laravel installation problem. If Laravel cannot write to storage or cache directories, applications fail with permission errors.

Symptoms include session errors, log writing failures, and view compilation problems. Resolution requires setting proper ownership (chown -R www-data:www-data) and permissions (chmod -R 775) for affected directories.

Web server user conflicts occur when files are owned by different users than the Apache process. Ensure consistent ownership across all Laravel files and directories.

PHP Extension Issues

Missing required PHP extensions prevent Laravel from functioning properly. Extension dependencies include curl, openssl, pdo, mbstring, tokenizer, and xml for core functionality.

Installation troubleshooting involves checking loaded extensions (php -m), installing missing packages, and restarting the web server. Version compatibility ensures extensions match your PHP version.

Package conflicts may arise from multiple PHP versions or incomplete uninstallations. Use php --version and which php to verify correct PHP binary usage.

Composer and Dependency Issues

Memory limit problems during Composer operations require increasing PHP memory limits or setting unlimited memory (COMPOSER_MEMORY_LIMIT=-1).

Network connectivity issues affect package downloads and updates. Verify internet access and consider using Composer mirrors for improved reliability in restricted networks.

Package conflict resolution involves understanding dependency relationships and using Composer’s conflict resolution tools. The composer why command helps identify dependency chains causing conflicts.

Apache Configuration Problems

Virtual host conflicts occur when multiple sites use the same ServerName or conflicting directory configurations. Ensure unique domain names and non-overlapping document roots.

Rewrite module issues prevent Laravel’s routing system from functioning. Verify mod_rewrite is enabled (a2enmod rewrite) and AllowOverride is set to All in virtual host configurations.

Document root problems arise from incorrect path specifications or permission issues. Ensure the virtual host points to Laravel’s public directory, not the application root.

Database Connection Issues

Authentication problems result from incorrect credentials or user permissions. Verify database user exists, has proper permissions, and can connect from the application server.

Connection timeout issues indicate network problems or database server overload. Check database server status and network connectivity between application and database servers.

Character set and collation problems cause data corruption or encoding errors. Ensure database, tables, and connection all use consistent UTF8MB4 configuration.

Security Hardening and Best Practices

Production Laravel installations require additional security measures beyond basic installation and configuration.

File System Security

Production file permissions should be more restrictive than development environments. Set files to 644 and directories to 755, with storage and cache directories remaining at 775 for write access.

Secure sensitive files including .env, composer files, and configuration data. The .env file should never be accessible via web browsers and must be excluded from version control systems.

Directory access restrictions prevent unauthorized file browsing. Ensure only the public directory is accessible through the web server, with all other Laravel directories protected from direct access.

PHP Security Configuration

Disable dangerous PHP functions including exec, shell_exec, system, and eval in production environments. These functions pose security risks if exploited through application vulnerabilities.

Configure PHP error reporting for production use. Disable display_errors and log_errors to prevent information disclosure while maintaining error logging for debugging purposes.

Set appropriate memory and execution limits to prevent resource exhaustion attacks. Configure upload_max_filesize and post_max_size based on application requirements.

Apache Security Headers

Security headers provide additional protection against common web vulnerabilities. Configure headers including X-Frame-Options, X-XSS-Protection, and Content-Security-Policy in your virtual host.

SSL/HTTPS setup encrypts data transmission and authenticates server identity. Obtain certificates from Let’s Encrypt or commercial providers and configure redirect rules from HTTP to HTTPS.

HTTP security best practices include disabling unnecessary Apache modules, hiding server version information, and implementing proper CORS policies for API endpoints.

Laravel Security Features

Built-in security features include CSRF protection, SQL injection prevention, and XSS filtering. Ensure these protections remain enabled and properly configured in production environments.

CSRF protection validates form submissions and AJAX requests. Configure CSRF middleware and include tokens in all forms and API calls requiring state modification.

Input validation and sanitization prevent malicious data from entering your application. Use Laravel’s validation rules and sanitization methods for all user inputs.

Performance Optimization Tips

Optimizing Laravel performance ensures responsive applications and efficient resource utilization.

Caching Configuration

Application caching improves performance by storing frequently accessed data in memory or fast storage. Configure cache drivers including Redis, Memcached, or file-based caching based on your infrastructure.

Route caching eliminates route compilation overhead in production: php artisan route:cache. This optimization provides significant performance improvements for applications with complex routing.

Configuration caching reduces file system access: php artisan config:cache. Cached configurations load faster and improve application bootstrap performance.

Database Optimization

Query optimization involves analyzing slow queries and adding appropriate indexes. Use Laravel’s query builder efficiently and implement database query caching for expensive operations.

Database indexing considerations include primary keys, foreign keys, and frequently queried columns. Monitor query performance and add indexes based on actual usage patterns.

Connection pooling setup reduces database connection overhead in high-traffic applications. Configure connection limits and timeouts appropriate for your application load.

Web Server Optimization

Apache performance tuning includes enabling compression, configuring keep-alive connections, and optimizing worker processes. These modifications improve response times and server capacity.

Enable compression for text-based content including HTML, CSS, and JavaScript. Gzip compression reduces bandwidth usage and improves page load times significantly.

Static file handling optimization involves configuring appropriate cache headers and using content delivery networks for global applications. Separate static asset serving from application logic for improved performance.

Next Steps and Development Workflow

Successful Laravel installation opens opportunities for advanced development techniques and deployment strategies.

Development Environment Setup

Version control integration using Git enables collaborative development and code history tracking. Initialize Git repositories and configure appropriate .gitignore files to exclude sensitive and generated files.

IDE and editor recommendations include PHPStorm, Visual Studio Code with PHP extensions, and Vim with appropriate plugins. These tools provide syntax highlighting, debugging support, and Laravel-specific features.

Debugging tools setup includes Laravel Telescope for application monitoring, Xdebug for step-through debugging, and Laravel Debugbar for development insights.

Laravel Features to Explore

Artisan command-line tool provides extensive functionality for code generation, database management, and application maintenance. Learn common commands including make:controller, migrate, and queue:work.

Eloquent ORM basics include model creation, relationships, and query building. Laravel’s ORM simplifies database interactions while maintaining flexibility for complex queries.

Blade templating engine enables clean view organization with template inheritance, component systems, and secure data rendering. Master Blade syntax for efficient frontend development.

Routing and controllers organize application logic and handle HTTP requests. Understand route definitions, middleware, and controller patterns for maintainable applications.

Deployment Considerations

Production environment differences include caching optimizations, error handling configurations, and security hardening. Develop deployment checklists to ensure consistent production configurations.

Deployment automation tools including Laravel Forge, Envoyer, and custom deployment scripts reduce manual errors and improve deployment reliability.

Monitoring and maintenance involves log analysis, performance monitoring, and security updates. Implement monitoring solutions and establish maintenance schedules for production applications.

Congratulations! You have successfully installed Laravel. Thanks for using this tutorial to install Laravel PHP Framework on Debian 13 “Trixie”. For additional help or useful information, we recommend you check the official Laravel website.

VPS Manage Service Offer
If you don’t have time to do all of this stuff, or if this is not your area of expertise, we offer a service to do “VPS Manage Service Offer”, starting from $10 (Paypal payment). Please contact us to get the best deal!

r00t

r00t is an experienced Linux enthusiast and technical writer with a passion for open-source software. With years of hands-on experience in various Linux distributions, r00t has developed a deep understanding of the Linux ecosystem and its powerful tools. He holds certifications in SCE and has contributed to several open-source projects. r00t is dedicated to sharing her knowledge and expertise through well-researched and informative articles, helping others navigate the world of Linux with confidence.
Back to top button