GitHub Actions for Laravel Projects: Complete CI/CD Setup

GitHub Actions for Laravel Projects: Complete CI/CD Setup

Continuous Integration and Continuous Deployment (CI/CD) has become essential for modern Laravel development. GitHub Actions provides a powerful, integrated solution that can automatically test, build, and deploy your Laravel applications whenever you push code. In this comprehensive guide, we’ll set up a complete CI/CD pipeline that will transform how you ship Laravel applications.

Why GitHub Actions for Laravel?

GitHub Actions offers several advantages for Laravel projects. It’s deeply integrated with your repository, supports matrix builds for testing across multiple PHP versions, and provides excellent caching capabilities. Unlike external CI services, Actions run directly within GitHub’s infrastructure, eliminating the need for third-party integrations and API keys.

The cost-effectiveness is particularly appealing for smaller teams and open-source projects, as GitHub provides generous free minutes for public repositories and reasonable pricing for private ones.

Setting Up the Basic Workflow

Create a new file at .github/workflows/laravel.yml in your repository root. This workflow will trigger on every push and pull request to your main branches:

name: Laravel CI/CD

on:
  push:
    branches: [ main, develop ]
  pull_request:
    branches: [ main ]

jobs:
  test:
    runs-on: ubuntu-latest
    
    strategy:
      matrix:
        php-version: [8.1, 8.2, 8.3]
        
    services:
      mysql:
        image: mysql:8.0
        env:
          MYSQL_ROOT_PASSWORD: password
          MYSQL_DATABASE: laravel_test
        ports:
          - 3306:3306
        options: --health-cmd="mysqladmin ping" --health-interval=10s --health-timeout=5s --health-retries=3

    steps:
    - uses: actions/checkout@v4
    
    - name: Setup PHP
      uses: shivammathur/setup-php@v2
      with:
        php-version: ${{ matrix.php-version }}
        extensions: mbstring, dom, fileinfo, mysql, zip
        coverage: xdebug

This matrix configuration ensures your application works across different PHP versions, catching compatibility issues early.

Dependency Management and Caching

Efficient dependency management is crucial for fast builds. GitHub Actions provides excellent caching support for Composer:

    - name: Cache Composer dependencies
      uses: actions/cache@v3
      with:
        path: ~/.composer/cache
        key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }}
        restore-keys: ${{ runner.os }}-composer-

    - name: Install Composer dependencies
      run: composer install --prefer-dist --no-progress --no-interaction

    - name: Cache Node modules
      uses: actions/cache@v3
      with:
        path: ~/.npm
        key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
        restore-keys: ${{ runner.os }}-node-

    - name: Install Node dependencies
      run: npm ci

This caching strategy can reduce build times from minutes to seconds on subsequent runs, significantly improving your development velocity.

Environment Configuration

Laravel applications require proper environment configuration for testing. Create a comprehensive setup that mirrors your production environment:

    - name: Create .env file
      run: |
        cp .env.example .env
        echo "DB_CONNECTION=mysql" >> .env
        echo "DB_HOST=127.0.0.1" >> .env
        echo "DB_PORT=3306" >> .env
        echo "DB_DATABASE=laravel_test" >> .env
        echo "DB_USERNAME=root" >> .env
        echo "DB_PASSWORD=password" >> .env

    - name: Generate application key
      run: php artisan key:generate

    - name: Run database migrations
      run: php artisan migrate --force

    - name: Seed database
      run: php artisan db:seed --force

Comprehensive Testing Suite

A robust testing pipeline should include multiple types of tests and code quality checks:

    - name: Run PHPUnit tests
      run: vendor/bin/phpunit --coverage-clover=coverage.xml

    - name: Run Laravel Dusk tests
      run: php artisan dusk

    - name: Run PHP CS Fixer
      run: vendor/bin/php-cs-fixer fix --dry-run --diff

    - name: Run PHPStan static analysis
      run: vendor/bin/phpstan analyse

    - name: Upload coverage to Codecov
      uses: codecov/codecov-action@v3
      with:
        file: ./coverage.xml

This comprehensive approach ensures code quality, catches regressions, and maintains coding standards across your team.

Frontend Asset Building

Modern Laravel applications often include frontend build processes. Integrate these seamlessly:

    - name: Build frontend assets
      run: |
        npm run build
        
    - name: Test frontend
      run: npm test

Deployment Pipeline

For deployment, create a separate job that runs only after tests pass on the main branch:

  deploy:
    needs: test
    runs-on: ubuntu-latest
    if: github.ref == 'refs/heads/main' && github.event_name == 'push'
    
    steps:
    - uses: actions/checkout@v4
    
    - name: Deploy to production
      uses: easingthemes/ssh-deploy@main
      env:
        SSH_PRIVATE_KEY: ${{ secrets.SSH_PRIVATE_KEY }}
        REMOTE_HOST: ${{ secrets.REMOTE_HOST }}
        REMOTE_USER: ${{ secrets.REMOTE_USER }}
        SOURCE: "./"
        TARGET: "/var/www/html"
        EXCLUDE: "/node_modules/, /.git/, /.github/"

Security and Secrets Management

Store sensitive information like deployment keys and API tokens in GitHub Secrets. Never commit credentials to your repository. Use secrets for database passwords, API keys, and deployment credentials.

Advanced Features

Consider implementing additional features like automated security scanning with GitHub’s CodeQL, dependency vulnerability checking, and integration with project management tools. You can also set up different workflows for staging and production environments.

Conclusion

Implementing GitHub Actions for your Laravel projects creates a robust, automated pipeline that improves code quality, catches issues early, and streamlines deployments. This setup provides a solid foundation that you can extend based on your specific requirements.

The initial investment in setting up comprehensive CI/CD pays dividends in reduced bugs, faster deployments, and improved team confidence. Start with the basic configuration and gradually add more sophisticated features as your project grows.

Remember to regularly review and update your workflows to take advantage of new GitHub Actions features and maintain security best practices. Your future self (and your team) will thank you for the reliability and peace of mind that proper CI/CD brings to Laravel development.

Leave a Reply