SQL Conventions for Laravel
When working with Laravel, following consistent SQL conventions is crucial for maintaining a clean and efficient database structure. Below are some recommended conventions for naming tables, columns, keys, and indexing in a Laravel application.
- Table Names:
- Plural, snake_case (e.g.,
users,posts)
- Plural, snake_case (e.g.,
- Column Names:
- Snake_case (e.g.,
user_id,created_at)
- Snake_case (e.g.,
- Primary Keys:
id, auto-incrementing integer
- Foreign Keys:
- Related table name +
_id(e.g.,user_id)
- Related table name +
- Timestamps:
created_at,updated_at
- User Table:
CREATE TABLE users ( id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255) NOT NULL, email VARCHAR(255) UNIQUE NOT NULL, password VARCHAR(255) NOT NULL, remember_token VARCHAR(100), created_at TIMESTAMP NULL, updated_at TIMESTAMP NULL ); - Posts Table:
CREATE TABLE posts ( id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, user_id BIGINT UNSIGNED NOT NULL, title VARCHAR(255) NOT NULL, body TEXT NOT NULL, created_at TIMESTAMP NULL, updated_at TIMESTAMP NULL, FOREIGN KEY (user_id) REFERENCES users(id) ); - Pivot Table:
CREATE TABLE role_user ( user_id BIGINT UNSIGNED NOT NULL, role_id BIGINT UNSIGNED NOT NULL, PRIMARY KEY (user_id, role_id), FOREIGN KEY (user_id) REFERENCES users(id), FOREIGN KEY (role_id) REFERENCES roles(id) ); - Indexing Conventions:
- Define primary key (e.g.,
PRIMARY KEY (id)) - Index foreign keys (e.g.,
INDEX (user_id)) - Unique indexes for unique columns (e.g.,
UNIQUE (email))
- Define primary key (e.g.,
- Data Types Conventions:
BIGINT UNSIGNEDfor primary keys,INT UNSIGNEDfor foreign keysVARCHAR(255)for variable-length strings,TEXTfor longer textsTIMESTAMP, nullable by default for optional timestamps