Database Commands

Configure database connections, test connectivity, create databases, and manage your schema with Doctrine ORM integration.

db:setup - Interactive Database Configuration

An interactive wizard that guides you through setting up your database connection by updating your .env file with the correct credentials.

Command
php craftsman db:setup

Functionality

  • Interactively prompts for database configuration details
  • Supports MySQL, PostgreSQL, SQLite, and SQL Server
  • Updates .env file with provided credentials
  • Tests the database connection automatically
  • Creates .env from .env.example if missing

Configuration Prompts

The wizard will ask for the following information:

Prompt Default Description
Database Driver mysql Database type: mysql, pgsql, sqlite, sqlsrv
Database Host localhost Database server hostname or IP
Database Port 3306 (MySQL) Database server port (varies by driver)
Database Name zephyrphp Name of the database to use
Database Username root Database user with access rights
Database Password (empty) Password for database user

Example Session

$ php craftsman db:setup

Database Setup Wizard
=====================

Database Driver [mysql]: mysql
Database Host [localhost]: localhost
Database Port [3306]: 3306
Database Name [zephyrphp]: my_project
Database Username [root]: dbuser
Database Password []: ********

Testing database connection...
✓ Database connection successful!

Configuration saved to .env file.

Environment Variables Updated

The command updates the following variables in your .env file:

DB_DRIVER=mysql
DB_HOST=localhost
DB_PORT=3306
DB_NAME=my_project
DB_USERNAME=dbuser
DB_PASSWORD=********

Common Use Cases

Fresh Installation

# First-time database configuration
php craftsman db:setup

# Then create the database
php craftsman db:create

# Finally, create schema
php craftsman db:schema

Changing Database Servers

# Reconfigure for a different database
php craftsman db:setup

# Update schema on new database
php craftsman db:schema

SQLite Configuration

$ php craftsman db:setup

Database Driver [mysql]: sqlite
Database Path [storage/database.sqlite]: storage/app.db

✓ SQLite database file created successfully!
Security Note

Never commit your .env file to version control. Ensure it's listed in .gitignore to protect your database credentials.

db:create - Create Database

Creates the database specified in your .env configuration if it doesn't already exist.

Command
php craftsman db:create

Functionality

  • Reads database configuration from .env
  • Connects to database server (without database name)
  • Creates the database if it doesn't exist
  • Reports if database already exists
  • Supports MySQL, PostgreSQL, and SQLite

Examples

# Create the configured database
php craftsman db:create

# Output when database doesn't exist:
✓ Database 'my_project' created successfully!

# Output when database already exists:
ℹ Database 'my_project' already exists.

Typical Workflow

# 1. Configure database connection
php craftsman db:setup

# 2. Create the database
php craftsman db:create

# 3. Install database module if needed
php craftsman add database

# 4. Create models
php craftsman model:wizard

# 5. Generate schema from models
php craftsman db:schema

db:test - Test Database Connection

Tests your database connection using the credentials in your .env file to verify everything is configured correctly.

Command
php craftsman db:test

Functionality

  • Attempts to connect to the database
  • Displays connection status (success or failure)
  • Shows error details if connection fails
  • Verifies database exists
  • Checks credentials are valid

Examples

# Test successful connection
$ php craftsman db:test

Testing database connection...
✓ Database connection successful!
Connected to: mysql://localhost:3306/my_project

# Test failed connection
$ php craftsman db:test

Testing database connection...
✗ Database connection failed!
Error: Access denied for user 'dbuser'@'localhost' (using password: YES)

When to Use

  • After configuration: Verify db:setup worked correctly
  • Debugging: Diagnose database connection issues
  • Environment changes: Verify credentials after server migration
  • Before deployment: Ensure production database is accessible

Troubleshooting

Access Denied Errors

# Check username and password in .env
DB_USERNAME=correct_user
DB_PASSWORD=correct_password

# Verify user has permissions in database
GRANT ALL PRIVILEGES ON my_project.* TO 'dbuser'@'localhost';

Connection Refused

# Verify database server is running
sudo service mysql status    # Linux
brew services list          # macOS
net start MySQL80           # Windows

# Check host and port in .env
DB_HOST=localhost
DB_PORT=3306

Database Not Found

# Create the database first
php craftsman db:create

# Or create manually
CREATE DATABASE my_project;

db:schema - Create/Update Database Schema

Synchronizes your database schema with your Doctrine ORM entity models. Creates tables, columns, indexes, and relationships based on your model definitions.

Command
php craftsman db:schema

Functionality

  • Analyzes all entity models in src/Models/
  • Compares current database schema with entity definitions
  • Generates SQL to create/modify tables
  • Creates tables for new entities
  • Adds new columns to existing tables
  • Creates indexes and foreign keys
  • Preserves existing data during updates
Important: Schema Updates

This command creates new tables and adds new columns, but it does not drop existing columns or tables. This is a safety feature to prevent accidental data loss. If you need to remove columns, you must do so manually or use migrations.

Examples

# Generate schema for all models
$ php craftsman db:schema

Analyzing entity models...
Found 3 entities: User, Post, Comment

Generating schema updates...
✓ Created table: users
✓ Created table: posts
✓ Created table: comments
✓ Created foreign key: posts.user_id → users.id
✓ Created foreign key: comments.post_id → posts.id
✓ Created index on users.email

Schema updated successfully!

Development Workflow

Initial Schema Creation

# 1. Create your models
php craftsman model:wizard

# 2. Generate database schema
php craftsman db:schema

# 3. Verify tables were created
php craftsman db:test

Adding a New Model

# 1. Create new model
php craftsman make:model Product

# 2. Update schema (only creates Product table)
php craftsman db:schema

# Existing tables (users, posts) are unchanged

Modifying an Existing Model

# 1. Edit your model file (e.g., add new property)
# src/Models/User.php
#[Column(type: 'string', length: 20)]
private string $phone;

# 2. Update schema (adds phone column to users table)
php craftsman db:schema

# Output:
✓ Added column: users.phone (varchar(20))

What Gets Created

Based on your model annotations, the command creates:

Annotation Database Element Example
#[Entity] Table CREATE TABLE users
#[Column] Column ALTER TABLE users ADD email VARCHAR(255)
#[Id] Primary Key PRIMARY KEY (id)
#[GeneratedValue] Auto-increment AUTO_INCREMENT
#[ManyToOne] Foreign Key FOREIGN KEY (user_id) REFERENCES users(id)
#[Index] Index CREATE INDEX idx_email ON users(email)
#[UniqueConstraint] Unique Index UNIQUE KEY (email)

Safety Features

Data Protection
  • Non-destructive: Never drops tables or columns automatically
  • Additive only: Only creates new tables and adds new columns
  • Preserves data: Existing data remains intact
  • Dry-run mode: Shows SQL without executing (use --dump-sql if available)

Best Practices

Development Environment

# Safe to run repeatedly during development
php craftsman db:schema

# It's idempotent - running it multiple times is safe

Production Environment

Production Warning

In production, consider using migrations instead of db:schema for better control and tracking of schema changes. The db:schema command is best suited for development and initial deployments.

Version Control

# Commit model changes
git add src/Models/User.php
git commit -m "Add phone field to User model"

# Document schema changes in commit message or migrations

Complete Database Workflow

Here's a complete example of setting up a database from scratch:

# Step 1: Configure database connection
php craftsman db:setup
# Enter: mysql, localhost, 3306, blog_db, dbuser, password

# Step 2: Create the database
php craftsman db:create
# Output: ✓ Database 'blog_db' created successfully!

# Step 3: Install database module (if not already installed)
php craftsman add database
# Output: ✓ Database module installed and enabled

# Step 4: Create your models
php craftsman model:wizard
# Create User model with id, name, email, password
# Create Post model with id, title, content, user_id

# Step 5: Generate database schema
php craftsman db:schema
# Output: ✓ Created tables: users, posts
#         ✓ Created foreign key: posts.user_id → users.id

# Step 6: Verify everything works
php craftsman db:test
# Output: ✓ Database connection successful!

# Step 7: Start developing
php craftsman serve

Troubleshooting

Database Module Not Installed

If you get "Database module not found" errors:

# Install the database module
php craftsman add database

# Verify it's enabled
php craftsman module:list

Permission Errors

If schema creation fails with permission errors:

# Grant necessary privileges to database user
GRANT CREATE, ALTER, INDEX, REFERENCES ON blog_db.* TO 'dbuser'@'localhost';
FLUSH PRIVILEGES;

Table Already Exists

If you get "table already exists" errors:

# This is usually safe to ignore - the command is idempotent
# The table already exists and won't be modified

# To recreate from scratch (WARNING: destroys data):
DROP DATABASE blog_db;
php craftsman db:create
php craftsman db:schema

Entity Not Found

If models aren't being detected:

# Ensure models are in the correct location
ls src/Models/

# Ensure models have proper namespace
namespace App\Models;

# Ensure models have Entity annotation
#[Entity]
class User { ... }

Next Steps

Now that you understand database management: