Currently Available: Need a skilled Software Developer for your next project?
Categories
Laravel

Adding Laravel Sail to Existing Projects: Solving the Database Driver Chicken-and-Egg Problem

When trying to add Laravel Sail to an existing project, you often encounter a classic catch-22 situation. You need to run php artisan sail:install to set up your containers, but your application code tries to access the database as soon as Artisan boots.

This commonly happens when your application contains code like:

if (\Schema::hasTable('sometable')) { … }

Since you're using the minimal laravelsail/phpXX-composer image (which doesn't include pdo_mysql) and your database containers aren't running yet, you get:

Illuminate\Database\QueryException
could not find driver

You can't set up the database because Artisan won't run, and Artisan won't run because the database isn't set up.

Solution: Use SQLite as a temporary database

  1. Create a temporary database file

    mkdir -p database
    touch database/database.sqlite
  2. Configure Laravel to use SQLite when running commands in the composer image

    docker run --rm \
    -u "$(id -u):$(id -g)" \
    -v "$(pwd):/var/www/html" \
    -w /var/www/html \
    -e DB_CONNECTION=sqlite \
    -e DB_DATABASE=/var/www/html/database/database.sqlite \
    laravelsail/php81-composer:latest \
    php artisan <your-command>

The image includes pdo_sqlite by default, allowing Laravel to boot successfully and complete the post-install scripts. You can then proceed with:

php artisan sail:install --with=mysql,redis,mailpit

Continue using the same environment variables for subsequent commands.

How this approach works

Laravel determines its database driver at runtime based on environment variables. The pdo_sqlite extension is included in all official PHP builds, including minimal ones, while pdo_mysql is not. By temporarily switching the driver for these one-time commands, you avoid the need to install additional extensions or modify application code.

Returning to MySQL after Sail setup

Once you start the complete Sail stack with ./vendor/bin/sail up -d, you'll be running a full PHP image that includes pdo_mysql.

Your .env file can then be configured with:

DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3306

Everything will function normally from this point forward.

What I'm building

Delegate tasks. Get software.

Give Vroni a GitHub issue, bug report, spec, or rough idea. It reads the repo, plans the change, writes code, runs checks, and works toward a review-ready pull request.

Take a look at vroni.com

Subscribe to my newsletter

Get new posts when I publish them.

I respect your privacy. Unsubscribe at any time.

Leave a Reply

Your email address will not be published. Required fields are marked *