1. Aug 2025 · by Emily C.
·

How to Use Git in CI/CD for Laravel

Git plays a central role in automating testing, integration, and deployment for Laravel projects. With Git, you can:

  • Version Control: Track changes and collaborate seamlessly.

  • Automate Workflows: Trigger CI/CD pipelines using GitHub Actions.

  • Enhance Code Quality: Use pre-commit checks and code coverage tools.

  • Simplify Deployment: Integrate Docker for consistent environments.

Key Steps to Get Started:

  1. Set Up Git: Initialize your Laravel project, configure .gitignore, and connect to GitHub.

  2. Automate CI/CD: Use GitHub Actions for testing and deployment.

  3. Use Docker: Ensure consistent Laravel deployments with containerization.

  4. Track Quality: Add pre-commit hooks and monitor code coverage with tools like OtterWise.

By combining Git with Laravel CI/CD workflows, you can save time, reduce errors, and maintain high code quality throughout your project.

Creating a CI/CD Pipeline in Laravel with Github Actions

Git Setup for Laravel

Setting up Git for your Laravel project is crucial for automating workflows like testing and deployment. Here's how to get started.

Start Git in Laravel

Follow these steps to initialize Git and link your Laravel project to GitHub:

  1. Initialize the repository: Open your Laravel project directory and run:

    git init
    git add .
    git commit -m "Initial Laravel project setup"
    
  2. Update .gitignore: Laravel's default .gitignore file excludes many unnecessary files. Add these entries for CI/CD purposes:

    /storage/coverage
    .env.testing
    .phpunit.result.cache
    
  3. Connect to GitHub: Create a repository on GitHub and link it to your local project:

    git remote add origin https://github.com/username/your-laravel-project.git
    git branch -M main
    git push -u origin main
    

Once Git is set up, you can move on to configuring Laravel for automated testing and deployment.

Laravel CI/CD Setup

Prepare your Laravel project for testing and deployment with these steps:

  1. Environment Configuration

    Create a .env.testing file specifically for testing:

    APP_ENV=testing
    DB_CONNECTION=sqlite
    DB_DATABASE=:memory:
    CACHE_DRIVER=array
    SESSION_DRIVER=array
    QUEUE_DRIVER=sync
    
  2. PHPUnit Configuration

    Modify phpunit.xml to enable code coverage reporting:

    <coverage>
        <include>
            <directory suffix=".php">./app</directory>
        </include>
        <report>
            <clover outputFile="build/logs/clover.xml"/>
        </report>
    </coverage>
    
  3. Code Coverage Setup

    Install a tool for generating code coverage reports. PCOV is recommended for its speed, but XDebug is another option if you need detailed debugging:

    pecl install pcov
    # Or, for XDebug
    pecl install xdebug
    

    Here's a quick comparison of these tools:

    Coverage Tool Benefits Complexity
    PCOV Faster, low overhead Simple
    XDebug Detailed reports, debugging Requires extra setup

With these steps completed, your Laravel project is ready for CI/CD workflows. The generated Clover XML reports can also be used for tracking code quality with tools like OtterWise.

GitHub Actions Workflow Setup

Automate your Laravel testing and deployment processes with GitHub Actions workflows. Here's how to set up the necessary files and workflows for seamless CI/CD integration.

Create Workflow Files

First, create the directory and file for your workflow:

mkdir -p .github/workflows
touch .github/workflows/laravel.yml

GitHub automatically detects YAML workflows placed in the .github/workflows directory.

Basic Laravel Workflow

Below is a sample workflow configuration for Laravel:

name: Laravel CI

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

jobs:
  laravel-tests:
    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v3

    - name: Setup PHP
      uses: shivammathur/setup-php@v2
      with:
        php-version: '8.2'
        extensions: mbstring, xml, pcov
        coverage: pcov

    - name: Copy .env
      run: cp .env.example .env.testing

    - name: Install Dependencies
      run: composer install -q --no-ansi --no-interaction --no-scripts --no-progress

    - name: Generate key
      run: php artisan key:generate --env=testing

    - name: Run Tests
      run: vendor/bin/phpunit --coverage-clover=build/logs/clover.xml

    - name: Upload Coverage
	  env:
	    OTTERWISE_TOKEN: ${{ secrets.OTTERWISE_TOKEN }}
	  run: bash <(curl -s https://raw.githubusercontent.com/getOtterWise/bash-uploader/main/uploader.sh)

This workflow triggers automatically when changes are pushed to the main or develop branches, or when pull requests target these branches. You can modify workflows to match the specific requirements of different branches.

Branch-Specific Workflows

Customize workflows based on branch type and purpose:

Branch Type Workflow Focus Typical Actions
Main Production deployment Full test suite, code coverage, deploy
Develop Integration testing Full test suite, code coverage
Feature Quick validation Basic tests, linting

Here’s an example of a lightweight workflow for feature branches:

name: Feature Branch CI

on:
  push:
    branches: [ 'feature/*' ]

jobs:
  quick-tests:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v3

    - name: Setup PHP
      uses: shivammathur/setup-php@v2
      with:
        php-version: '8.2'

    - name: Run Quick Tests
      run: vendor/bin/phpunit --testsuite=unit

For feature branches, this workflow focuses on running basic tests quickly, ensuring faster feedback during development.

Additional Optimization Tips

  • Cache dependencies to save time.

  • Use specific version tags for better stability.

  • Set timeouts to avoid hanging builds.

  • Enable workflow concurrency limits to prevent overlapping runs.

OtterWise can integrate with GitHub's status checks, providing detailed coverage reports directly in pull requests without requiring access to your source code. This helps maintain code quality before merging changes.

Monitor Your Test Quality

With OtterWise, you can track Code Coverage, contributor stats, code quality, and much more.

Laravel Deployment Methods

Using Docker for Laravel deployments ensures consistent performance across different environments, simplifying the process.

Docker-Based Deployment

Here’s a Dockerfile you can use as a foundation for deploying your Laravel application:

FROM php:8.2-fpm

# Install required system packages
RUN apt-get update && apt-get install -y \
    git \
    curl \
    libpng-dev \
    libonig-dev \
    libxml2-dev \
    zip \
    unzip

# Install PHP extensions
RUN docker-php-ext-install pdo_mysql mbstring exif pcntl bcmath gd

# Add Composer to the image
COPY --from=composer:latest /usr/bin/composer /usr/bin/composer

# Set the working directory
WORKDIR /var/www

# Copy application files
COPY . /var/www

# Install dependencies
RUN composer install --optimize-autoloader --no-dev

# Cache configurations for better performance
RUN php artisan config:cache && \
    php artisan route:cache && \
    php artisan view:cache

# Set proper permissions
RUN chown -R www-data:www-data /var/www

To integrate Docker with your CI/CD pipeline, you can use the following GitHub Actions workflow:

name: Docker Deploy

on:
  push:
    branches: [ production ]

jobs:
  build-and-push:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3

      - name: Build Docker image
        run: docker build -t myapp:${{ github.sha }} .

      - name: Push to registry
        run: |
          docker tag myapp:${{ github.sha }} registry.example.com/myapp:${{ github.sha }}
          docker push registry.example.com/myapp:${{ github.sha }}

This workflow automates the creation and delivery of Docker images, offering better control and traceability.

Feature Description
Isolation Keeps the application consistent across different environments.
Scalability Makes it easier to scale horizontally using container orchestration tools.
Version Control Uses Git commit hashes to tag Docker images, ensuring traceability.
Resource Management Allows precise allocation of resources to containers.

To further refine the deployment process, implement automated health checks that validate your application’s status before finalizing deployments:

healthcheck:
  test: ["CMD", "php", "artisan", "health:check"]
  interval: 30s
  timeout: 10s
  retries: 3
  start_period: 30s

These health checks, combined with container tagging, ensure a reliable and efficient deployment process.

Code Quality Management

Keeping your Laravel application's code quality high means incorporating automated checks at every stage of your CI/CD pipeline.

Git Pre-Commit Checks

Set up Git hooks to automate quality checks before committing code. Create a .git/hooks/pre-commit file with the following script:

#!/bin/sh
php artisan test
php artisan phpcs
php artisan phpstan

Make sure the hooks are executable and consistent for all team members. Common Git hooks include pre-commit, pre-push, and post-merge, which can handle tasks like running tests, linting code, or clearing caches.

Code Coverage with OtterWise

OtterWise

After enforcing local quality with pre-commit checks, enhance your CI pipeline by adding code coverage reporting. OtterWise offers detailed code coverage tracking for Laravel projects without needing access to your source code.

To integrate OtterWise, ensure PHPUnit generates a Clover XML report. Update your GitHub Actions workflow with this step:

- name: Run Tests with Coverage
  run: |
    php artisan test --coverage-clover clover.xml

OtterWise processes these reports and provides insights via its dashboard. Here's what you can expect:

  • Pull Request Status Checks
    Prevent merging code that drops coverage below your set thresholds. Configure these checks in your repository settings to enforce quality standards.

  • Coverage Visualization
    OtterWise creates detailed graphs showing coverage trends across branches, helping your team pinpoint areas needing additional tests.

  • API Integration
    Use the OtterWise API to programmatically access coverage data and integrate it into your team's dashboards:

    $response = Http::withToken('your-api-token')
        ->get('https://otterwise.app/api/github/your-org/your-repo');
    

To get the most out of OtterWise, set it up to:

  • Exclude generated files and vendor directories.

  • Define minimum coverage thresholds for specific directories.

  • Automatically add comments to pull requests with coverage changes.

  • Trigger failure conditions when coverage drops below acceptable levels.

Summary

Integrating Git into your Laravel CI/CD pipeline sets the stage for automated testing, deployment, and maintaining code quality. This approach simplifies development workflows and ensures high standards are upheld throughout your project.

Tracking code coverage is an essential part of this process. Tools like OtterWise can help you measure how effective your tests are. By keeping an eye on coverage metrics and adding quality checks to pull requests, you can maintain strong test coverage as your project grows. Visualizing these trends also helps teams pinpoint areas that need more attention.

Here’s how to make the most of Git in your Laravel CI/CD pipeline:

  • Automate Quality Checks: Set up Git hooks to run local checks automatically.

  • Track Code Coverage: Use coverage metrics to guide your testing priorities.

  • Maintain Standards: Add pull request checks to enforce quality benchmarks.

  • Document Processes: Create clear workflows to keep your team on the same page.

These practices create a smooth and efficient Laravel deployment process. By combining automated tools with well-documented workflows, you can maintain high code quality without slowing down development.

FAQs

How can I streamline my Laravel CI/CD pipeline for better speed and reliability with GitHub Actions?

To make your Laravel CI/CD pipeline faster and more reliable with GitHub Actions, focus on automation and code quality. Use tools like OtterWise to monitor code health, track coverage metrics, and identify potential issues - all without requiring access to your code. This ensures your codebase remains robust and your deployments are efficient.

By incorporating automated checks and detailed reporting, you can catch problems early, maintain high-quality standards, and accelerate your development process.

What are the advantages of using Docker for Laravel deployments in a CI/CD pipeline, and how does it ensure consistency across environments?

Using Docker for Laravel deployments in a CI/CD pipeline offers several key benefits. Docker allows you to package your application and its dependencies into a lightweight, portable container, ensuring that your application behaves the same way across development, staging, and production environments. This eliminates the classic "it works on my machine" problem.

By standardizing environments, Docker improves consistency and reduces deployment errors. It also simplifies scaling, as containers can be easily replicated and managed. Additionally, Docker integrates seamlessly with CI/CD pipelines, enabling automated builds, tests, and deployments while maintaining a clean and predictable workflow for your Laravel projects.

How can I use OtterWise to monitor code coverage and maintain quality standards in my Laravel project?

OtterWise makes it easy to monitor code coverage and maintain high-quality standards in your Laravel project without requiring access to your code. It provides tools like pull request status checks to ensure your code meets quality benchmarks before merging.

With detailed reporting and insights, you can quickly identify areas for improvement, track your project's health over time, and collaborate effectively with your team. OtterWise is designed to streamline your workflow while keeping your code secure and maintainable.

Improve code quality today_

With OtterWise, you can track Code Coverage, contributor stats, code health, and much more.