0
0
LaravelHow-ToBeginner · 3 min read

How to Use Artisan Migrate in Laravel: Syntax and Examples

Use the php artisan migrate command in your Laravel project root to run all pending database migrations. This command updates your database schema based on migration files in the database/migrations folder.
📐

Syntax

The basic syntax for running migrations is php artisan migrate. You can add options like --force to run migrations in production or --step to run migrations step-by-step.

  • php artisan migrate: Runs all pending migrations.
  • --force: Runs migrations without confirmation (useful in production).
  • --step: Runs migrations one batch at a time.
bash
php artisan migrate
php artisan migrate --force
php artisan migrate --step
💻

Example

This example shows running migrations to create tables defined in migration files. It updates the database schema to match your Laravel migrations.

bash
cd your-laravel-project
php artisan migrate
Output
Migrating: 2024_06_01_000000_create_users_table Migrated: 2024_06_01_000000_create_users_table (0.05 seconds) Migrating: 2024_06_01_000001_create_posts_table Migrated: 2024_06_01_000001_create_posts_table (0.04 seconds)
⚠️

Common Pitfalls

Common mistakes include:

  • Running php artisan migrate without setting up the database connection in .env.
  • Forgetting to create migration files before running the command.
  • Not using --force when running migrations in production, causing the command to stop.
  • Trying to run migrations when the database user lacks permissions.

Always check your database config and permissions before migrating.

bash
Wrong (missing DB config):
php artisan migrate

Right (with .env DB setup):
# Set DB_CONNECTION, DB_DATABASE, DB_USERNAME, DB_PASSWORD in .env
php artisan migrate --force
📊

Quick Reference

CommandDescription
php artisan migrateRun all pending migrations
php artisan migrate:rollbackUndo the last batch of migrations
php artisan migrate:resetUndo all migrations
php artisan migrate:refreshRollback all and re-run all migrations
php artisan migrate --forceRun migrations in production without confirmation

Key Takeaways

Run php artisan migrate to apply all new migrations to your database.
Ensure your database connection is correctly set in the .env file before migrating.
Use --force to run migrations safely in production environments.
Check database user permissions to avoid migration failures.
Use rollback and refresh commands to manage migration history effectively.