GitHub Actions for an existing Laravel app · Part 1 of 3
Checks on every pull request
The tests made honest on MySQL first, then one workflow: Pint, Larastan, composer audit, the suite on MySQL and Redis service containers, and the Vite build, in parallel, cached, once per push.
By Abhishek Fouzdar · Updated
By the end of this part, every push to a pull request runs five checks on GitHub's machines and reports next to the merge button: code style, static analysis, a dependency audit, the test suite against MySQL and Redis, and the frontend build. Deploys come in parts 2 and 3; they will reuse this workflow unchanged, which is why it is worth getting right first.
The one idea to hold on to
A workflow is a YAML file in .github/workflows/. It names the events that trigger it, and it contains jobs. Each job gets a fresh Ubuntu virtual machine, runs its steps from top to bottom, and is thrown away. Jobs run in parallel unless one says it needs another. A step is either a shell command or an action, which is a reusable step someone published, like "install PHP 8.4" or "check out the repository".
That is the whole model. Everything below is a consequence of it: the machine is empty, so every job installs what it needs; jobs do not share files, so each one checks out the code again; and the only thing that survives from one run to the next is what you deliberately cache.
First, make the tests honest
Laravel's phpunit.xml points the test suite at SQLite in memory. It is a sensible default for a laptop, but it means the suite never sees the database the app runs on. SQLite is forgiving about types, lengths and GROUP BY in ways MySQL is not, so a migration or a query can pass every test and fail in production. If CI is going to run the tests, it should run them on the real thing.
Two lines in phpunit.xml become one:
<!-- before -->
<env name="DB_CONNECTION" value="sqlite"/>
<env name="DB_DATABASE" value=":memory:"/>
<!-- after -->
<env name="DB_DATABASE" value="testing"/>
The connection now comes from .env, which in the Docker setup is MySQL on the db container, and the database is a separate testing one, so RefreshDatabase never touches your data. The MySQL image creates that database on the first start of a new volume if a script asks it to. Create docker/mysql/init/testing.sh:
#!/bin/sh
# Sourced by the MySQL image's entrypoint the first time the db volume is created.
# A second database for the test suite, so RefreshDatabase never touches your data.
docker_process_sql <<-EOSQL
CREATE DATABASE IF NOT EXISTS testing;
GRANT ALL ON testing.* TO '$MYSQL_USER'@'%';
EOSQL
And mount the folder in compose.yaml, under the db service's volumes:
volumes:
- dbdata:/var/lib/mysql
# Runs once, on a new volume: creates the `testing` database for the test suite.
- ./docker/mysql/init:/docker-entrypoint-initdb.d:ro
Do not make the script executable. The MySQL image runs executable .sh files as separate programs, where docker_process_sql does not exist; it sources the non-executable ones inside its own entrypoint, where it does. Git tracks the executable bit, so this matters for everyone who clones.
The script only runs when the volume is new. On a stack that already exists, create the database once by hand:
docker compose exec db mysql -uroot -psecret \
-e "CREATE DATABASE IF NOT EXISTS testing; GRANT ALL ON testing.* TO 'app'@'%';"
secret and app are the defaults from the Docker series; use yours.
Tests worth running
The example app had Laravel's placeholder test, which requests / and checks for a 200. A pipeline that runs only that proves the pipeline works, not the app. Three files replace it, each exercising one thing the app actually does. For how to write a real suite, with Pest, fakes, factories, coverage and browser tests, see the testing series; its part 5 has a workflow with coverage and a MySQL service, which runs on every push because that repository is a public demo with no deploy, the case this part's trigger rules are not about.
tests/Feature/SignupTest.php, for the route that queues a mail and the job that sends it:
<?php
namespace Tests\Feature;
use App\Jobs\SendWelcomeMail;
use App\Mail\WelcomeMail;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Queue;
use Tests\TestCase;
class SignupTest extends TestCase
{
public function test_signup_queues_a_welcome_mail(): void
{
Queue::fake();
$this->get('/signup/[email protected]')
->assertOk()
->assertSee('Queued a welcome mail for [email protected].');
Queue::assertPushed(SendWelcomeMail::class, fn (SendWelcomeMail $job) => $job->email === '[email protected]');
}
public function test_the_job_sends_the_mail_to_the_address(): void
{
Mail::fake();
(new SendWelcomeMail('[email protected]'))->handle();
Mail::assertSent(WelcomeMail::class, fn (WelcomeMail $mail) => $mail->hasTo('[email protected]'));
}
}
Queue::fake() replaces the queue with one that records what was pushed, so the test can assert the job was dispatched with the right address without running it. Mail::fake() does the same for mail, so the second test runs the job's handle() directly and checks what it would have sent.
tests/Feature/HeartbeatTest.php, for the scheduled command:
<?php
namespace Tests\Feature;
use Tests\TestCase;
class HeartbeatTest extends TestCase
{
public function test_the_scheduled_command_runs(): void
{
$this->artisan('app:heartbeat')
->expectsOutput('heartbeat written')
->assertExitCode(0);
}
}
tests/Feature/UserTest.php, for the database:
<?php
namespace Tests\Feature;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class UserTest extends TestCase
{
// Migrates the `testing` database once per run and wraps each test in a transaction.
use RefreshDatabase;
public function test_users_are_stored_with_a_hashed_password(): void
{
$user = User::factory()->create(['email' => '[email protected]']);
$this->assertDatabaseHas('users', ['email' => '[email protected]']);
$this->assertNotSame('password', $user->password);
$this->assertTrue(password_verify('password', $user->password));
}
}
RefreshDatabase migrates the testing database once per run and wraps each test in a transaction it rolls back, so tests cannot see each other's rows. This is the test that proves the database connection is real: with the SQLite lines gone and no testing database, it fails.
Run them:
$ bin/dev test
PASS Tests\Unit\ExampleTest
✓ that true is true
PASS Tests\Feature\HeartbeatTest
✓ the scheduled command runs
PASS Tests\Feature\SignupTest
✓ signup queues a welcome mail
✓ the job sends the mail to the address
PASS Tests\Feature\UserTest
✓ users are stored with a hashed password
Tests: 5 passed (10 assertions)
Duration: 1.27s
Keep tests/Unit/ExampleTest.php. PHPUnit refuses to run when a directory listed in phpunit.xml does not exist, and deleting the last unit test deletes the directory.
The workflow
Create .github/workflows/ci.yml:
# Every push to a pull request: style, static analysis, dependency audit, the test suite
# against real MySQL and Redis, and the frontend build. The deploy workflows call this
# same workflow first (workflow_call), so nothing reaches the server that did not pass.
#
# Only pull_request, not push: listing both runs everything twice for every push to a
# branch with a PR open. A branch without a PR gets no CI, and that is the point.
name: CI
on:
pull_request:
workflow_call:
concurrency:
group: ci-${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
lint:
name: Style and analysis
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: shivammathur/setup-php@v2
with:
php-version: '8.4'
coverage: none
- id: composer-cache
run: echo "dir=$(composer config cache-files-dir)" >> "$GITHUB_OUTPUT"
- uses: actions/cache@v5
with:
path: ${{ steps.composer-cache.outputs.dir }}
key: composer-${{ hashFiles('composer.lock') }}
restore-keys: composer-
- name: Install dependencies
run: composer install --no-interaction --prefer-dist --no-progress
- name: Pint
run: vendor/bin/pint --test
- name: Larastan
run: vendor/bin/phpstan analyse --no-progress --memory-limit=1G
- name: Audit
run: composer audit
tests:
name: Tests
runs-on: ubuntu-latest
services:
mysql:
image: mysql:8.4
env:
MYSQL_DATABASE: testing
MYSQL_ROOT_PASSWORD: root
ports: ['3306:3306']
options: >-
--health-cmd "mysqladmin ping -h 127.0.0.1 -u root -proot"
--health-interval 5s --health-timeout 5s --health-retries 20
redis:
image: redis:7-alpine
ports: ['6379:6379']
options: >-
--health-cmd "redis-cli ping" --health-interval 5s --health-timeout 3s --health-retries 20
steps:
- uses: actions/checkout@v7
- uses: shivammathur/setup-php@v2
with:
php-version: '8.4'
extensions: pdo_mysql, redis, intl, bcmath
coverage: none
- id: composer-cache
run: echo "dir=$(composer config cache-files-dir)" >> "$GITHUB_OUTPUT"
- uses: actions/cache@v5
with:
path: ${{ steps.composer-cache.outputs.dir }}
key: composer-${{ hashFiles('composer.lock') }}
restore-keys: composer-
- name: Install dependencies
run: composer install --no-interaction --prefer-dist --no-progress
- name: Prepare the app
run: |
cp .env.example .env
php artisan key:generate --no-interaction
- name: Tests
env:
DB_CONNECTION: mysql
DB_HOST: 127.0.0.1
DB_PORT: 3306
DB_DATABASE: testing
DB_USERNAME: root
DB_PASSWORD: root
REDIS_HOST: 127.0.0.1
SESSION_DRIVER: redis
CACHE_STORE: redis
QUEUE_CONNECTION: redis
MAIL_MAILER: array
run: php artisan test
assets:
name: Frontend build
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/setup-node@v7
with:
node-version: '22'
cache: npm
- run: npm ci --no-audit --no-fund
- run: npm run build
Commit it, push a branch, open a pull request, and the three jobs appear under the pull request's checks within a few seconds. Everything below explains the choices.
Triggers
pull_request runs the workflow for every push to a branch that has a pull request open, against the merge of that branch into its base. workflow_call lets another workflow run this one as a job, which the deploy workflows in part 2 do, so main gets exactly the same checks before anything is built.
What is missing is push. The common pattern is to list both push and pull_request, and the result is that every push to a pull request branch runs every job twice, once for each event. The first version of this file did that; the fix was deleting the push trigger. The consequence is that a branch without a pull request gets no CI, and that is the intended practice: work goes through pull requests.
concurrency cancels a run that is still going when a newer push to the same branch arrives. Nobody needs the result for a commit that has already been replaced.
The lint job
shivammathur/setup-php installs the PHP version you name, with Composer, in a few seconds. Then composer install, then three commands that each exit non-zero on a problem, which fails the step, which fails the job:
pint --testreports style violations without fixing them. Fixing happens on the developer's machine, withpint.phpstan analyseis Larastan, at the level set inphpstan.neon. The memory limit is there because the default is too low for a Laravel app and the failure message when it runs out is not obvious.composer auditchecks the locked dependencies against the advisory database and fails on a known vulnerability. It is the cheapest security measure a project can have.
Before composer install is the cache. Composer keeps every package archive it downloads in a cache directory; the two steps save that directory under a key built from composer.lock and restore it on the next run. With the cache warm, composer install on a fresh machine takes a few seconds instead of downloading everything again. restore-keys means a run with a changed lock file still starts from the previous cache rather than from nothing.
The tests job
This job has services: containers GitHub starts next to the job's virtual machine before the steps run, and stops afterwards.
services:
mysql:
image: mysql:8.4
env:
MYSQL_DATABASE: testing
MYSQL_ROOT_PASSWORD: root
ports: ['3306:3306']
options: >-
--health-cmd "mysqladmin ping -h 127.0.0.1 -u root -proot"
--health-interval 5s --health-timeout 5s --health-retries 20
The image is the same one the Docker series runs, so the tests use the MySQL version production uses. ports publishes the container's port on the virtual machine, which is why the steps reach it at 127.0.0.1. The health check matters: without it, the first step can run before MySQL is accepting connections, and php artisan test fails with a connection refused that goes away on retry, which is the worst kind of failure. With it, GitHub waits until the check passes before starting the steps.
setup-php gets an extensions list here. The lint job does not need pdo_mysql or redis; this job does, because it talks to both services.
The env on the test step is where the environment is decided, and it is worth being precise about who wins, because three places can set DB_HOST:
- A real environment variable, which is what
env:in a workflow sets. Always wins. <env>inphpunit.xml. PHPUnit sets these only if the variable is not already set, unless the element hasforce="true"..env. Laravel loads it without overriding anything that already exists.
So the step's env block overrides both files. phpunit.xml keeps DB_DATABASE=testing and the array and sync drivers, which are right for a laptop. The workflow points DB_HOST at the service container, and switches the cache, session and queue drivers to Redis so that anything which only works on Redis, like atomic locks, is tested on Redis. You can check the precedence yourself: run the suite with a wrong database name in the environment and watch the database test fail.
$ docker compose exec -e DB_DATABASE=nope app php artisan test
FAIL Tests\Feature\UserTest
FAILED Tests\Feature\UserTest > users are stored with a… QueryException
Tests: 1 failed, 4 passed (7 assertions)
The prepare step copies .env.example to .env and generates a key, because the app will not boot without an APP_KEY and .env is not in the repository. Then php artisan test, with no flags. The first version had --no-interaction on it, out of habit from the other artisan commands; PHPUnit, which artisan test hands its arguments to, rejects it.
The assets job
setup-node with cache: npm does for npm what the Composer cache does for Composer, in one line, because the action has caching built in. npm ci installs exactly what package-lock.json says, and refuses to run if the lock file and package.json disagree, which is what you want on a machine that is supposed to be reproducible. npm run build is the Vite production build. The job proves the frontend compiles; the built files are thrown away with the virtual machine. Part 2 builds them again where they are needed.
Reading a failure
A red check on the pull request links to the run. The run page shows the three jobs; the failed one is expanded to the failed step; the step's log is the same output you would see in a terminal. For the test job that means the familiar FAILED Tests\Feature\... block with the assertion and the file and line. For Pint, the list of files and the rules they break. For Larastan, the file, the line and the message.
The habit to build is that a red check is read on GitHub, not reproduced locally first. It is usually faster, and it is always the same output everyone else sees.
Checkpoint
You should have:
phpunit.xmlwithDB_DATABASE=testingand no SQLite lines,docker/mysql/init/testing.sh(not executable) mounted intodb, andbin/dev testgreen on MySQL;- the three test files;
.github/workflows/ci.yml, and a pull request with three green checks on it.
Part 2 builds the thing that gets deployed: the production image for the Docker path, or the release tarball for a classic server.
New posts by email
Get new posts by email. Nothing else, no digests, unsubscribe in one click.
Comments
Comments are GitHub Discussions in shipbytes/discussions. Sign in with GitHub to post.
In this series
1 / 3- OverviewGitHub Actions for an existing Laravel app
- Part 1Checks on every pull request
- Part 2Building the release
- Part 3Deploying on every merge, and the team's practice