Mastering Build and Deploy Hooks in Laravel Vapor
Overview of Deployment Automation
Deploying a
Prerequisites
To follow this guide, you should be comfortable with the following:
- Basic Laravelframework architecture.
- A functioning Laravel Vaporaccount and the Vapor CLI.
- Familiarity with YAMLsyntax for configuration files.
- Understanding of NPMorComposerfor asset and dependency management.
Key Libraries & Tools
- Laravel Vapor CLI: The primary tool for initiating deployments and viewing real-time logs.
- vapor.yaml: The central configuration file where hook logic is defined.
- AWS (Amazon Web Services): The underlying infrastructure where your application and databases reside.
- Artisan: Laravel's command-line interface used within deploy hooks for tasks like migrations.
Code Walkthrough: Configuring Hooks
Open your vapor.yaml file to define how each environment behaves. You can customize commands per environment, such as choosing between development or production asset builds.
id: 1
name: my-app
environments:
staging:
build:
- 'composer install'
- 'npm install && npm run development'
- 'php artisan event:cache'
deploy:
- 'php artisan migrate --force'
production:
build:
- 'composer install --no-dev'
- 'npm install && npm run production'
In this configuration, the build section runs on your local machine or CI/CD environment before the code is zipped and uploaded. This is the ideal time for npm run production because it minimizes the final package size. The deploy section runs after the code is uploaded to php artisan migrate here because the command needs to interact with the
Syntax Notes
Practical Examples: Database Integration
Running migrations via deploy hooks requires a linked database. In the Vapor dashboard, create a database resource (e.g., my-staging-db). Once created, link it in your vapor.yaml so the environment knows where to run the migration commands:
staging:
database: my-staging-db
deploy:
- 'php artisan migrate --force'
Tips & Gotchas
One common pitfall is forgetting that build hooks lack access to your production database. Never put php artisan migrate in a build hook; it will fail because your local machine cannot (and should not) reach your cloud database directly. Conversely, avoid running heavy asset compilation in deploy hooks, as this consumes
