Use Tinker –execute for Automation

📖 2 minutes read

Ever tried to automate Laravel Tinker commands in a Docker container or CI pipeline? If you’ve used stdin piping with heredocs, you probably discovered it just… doesn’t work reliably.

I spent way too long debugging why docker exec php artisan tinker with piped PHP commands would run silently and produce zero output. Turns out, Tinker’s interactive mode doesn’t play nice with stdin automation.

The solution that actually works? The --execute flag.

// ❌ This doesn't work reliably:
docker exec my-app bash -c "php artisan tinker <<'EOF'
\$user = App\Models\User::first();
echo \$user->email;
EOF"

// ✅ This does:
docker exec my-app php artisan tinker --execute="
\$user = App\Models\User::first();
echo \$user->email;
"

// Or for multi-line commands in bash scripts:
docker exec my-app php artisan tinker --execute="$(cat <<'EOF'
$user = App\Models\User::first();
$user->email = '[email protected]';
$user->save();
echo 'Updated: ' . $user->email;
EOF
)"

The --execute flag runs Tinker in non-interactive mode. It evaluates the PHP code, prints the output, and exits cleanly. No TTY required, no stdin gymnastics, no mystery silent failures.

This is a lifesaver for:

  • CI/CD pipelines — seed data, run health checks, warm caches
  • Docker automation — scripts that need to interact with Laravel in containers
  • Cron jobs — quick data fixes without writing full artisan commands

Pro tip: for complex multi-statement logic, you can still pass a full PHP script to --execute. Just wrap it in quotes and keep newlines intact with $(cat <<'EOF' ... EOF).

Stop fighting with heredocs. Use --execute and move on with your life.

Daryle De Silva

VP of Technology

11+ years building and scaling web applications. Writing about what I learn in the trenches.

Comments

Leave a Reply

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