Database design is a crucial part of developing a robust and scalable application. Here are some rules and standards your developers should follow when working on database and table creation, as well as defining relationships:
Database Design Principles
-
Normalization
- Follow the principles of database normalization to reduce redundancy and improve data integrity.
- Aim for at least Third Normal Form (3NF) to ensure that the database is efficient and maintains data consistency.
-
Database Naming Conventions
- Use lowercase for all database, table, and column names.
- Use underscores (
_) to separate words in table and column names (e.g.,user_profiles,order_items). - Avoid using reserved keywords as table or column names.
- Use singular names for tables (e.g.,
user,order), though some prefer plural for clarity (e.g.,users,orders). Choose one convention and stick to it.
-
Primary Keys
- Always use an
idcolumn as the primary key, which should be an auto-incrementing integer. - For complex cases, consider using UUIDs as primary keys if needed.
- Always use an
-
Foreign Keys
- Define foreign keys to enforce referential integrity between related tables.
- Use descriptive names for foreign key columns (e.g.,
user_id,product_id). - Use
onDelete('cascade')where appropriate to ensure that related records are deleted when a parent record is removed.
-
Indexes
- Create indexes on columns that are frequently used in WHERE clauses, JOINs, or as foreign keys.
- Use composite indexes for queries involving multiple columns.
- Avoid over-indexing, as it can negatively impact write performance.
Table Creation Standards
-
Migrations
- Use Laravel migrations to create and modify database tables.
- Ensure that each migration is atomic and describes a single change to the database schema.
- Name migration files descriptively, reflecting the action they perform (e.g.,
create_users_table,add_status_to_orders).
-
Column Naming Conventions
- Use descriptive and consistent names for columns.
- Use
created_atandupdated_atfor timestamp columns, which Laravel will manage automatically with$table->timestamps(). - Use
deleted_atfor soft deletes with$table->softDeletes().
-
Data Types
- Choose appropriate data types for columns. For example, use
integerfor IDs,stringfor names,textfor longer descriptions, andbooleanfor true/false values. - Use
enumortinyIntegerfor status fields to enforce specific values. - Use
decimalorfloatfor monetary values, ensuring precision.
- Choose appropriate data types for columns. For example, use
-
Default Values
- Define default values for columns where applicable to avoid null values.
- Ensure that critical columns (e.g., status, type) have meaningful default values.
Defining Relationships
-
One-to-One Relationship
- Implement a one-to-one relationship using the
hasOneandbelongsTomethods in Eloquent models. - Example: A
Userhas oneProfile. - Migration: In the
profilestable, add auser_idforeign key.
- Implement a one-to-one relationship using the
|
// User model // Profile model |
2. One-to-Many Relationship
- Use
hasManyandbelongsTofor one-to-many relationships. - Example: A
Posthas manyComments. - Migration: In the
commentstable, add apost_idforeign key.
|
// Post model // Comment model |
3. Many-to-Many Relationship
- Implement many-to-many relationships using
belongsToManyin Eloquent models. - Use a pivot table to manage the relationship. The pivot table should have both foreign keys.
- Example: A
Userbelongs to manyRoles, and aRolebelongs to manyUsers. - Migration: Create a
role_userpivot table withuser_idandrole_idcolumns.
|
// User model // Role model |
4. Polymorphic Relationships
- Use polymorphic relationships for models that can belong to more than one type of model.
- Example: A
Commentmodel can be associated with bothPostandVideomodels. - Migration: In the
commentstable, addcommentable_idandcommentable_typecolumns.
|
// Comment model // Post and Video models |
Database Security and Integrity
-
Data Validation
- Validate data at both the application (Laravel validation) and database (database constraints) levels.
- Use Laravel's form requests for validation and define validation rules within the models or services.
-
Transactions
- Use database transactions for operations involving multiple queries to ensure data integrity.
- Example: When creating an order and deducting inventory, both actions should occur within a transaction to avoid inconsistencies.
| DB::transaction(function () { // Your code here }); |
-
Avoid Raw Queries
- Avoid using raw SQL queries unless absolutely necessary. Prefer Eloquent ORM or Query Builder for database operations to prevent SQL injection and ensure readability.
- If raw queries are necessary, use parameter binding to prevent SQL injection.
-
Data Encryption
- Encrypt sensitive data before storing it in the database.
- Use Laravel's built-in encryption functions or packages like
Laravel Encryptionfor this purpose.
Database Migration Versioning
-
Migration Files
- Keep migration files under version control to track changes in the database schema.
- Avoid modifying existing migration files after they have been applied. If changes are needed, create a new migration file.
-
Rollback and Refresh
- Ensure that every migration can be safely rolled back by implementing the
downmethod. - Use
php artisan migrate:rollbackto undo migrations andphp artisan migrate:refreshto reapply them.
- Ensure that every migration can be safely rolled back by implementing the
-
Database Seeding
- Use seeders to populate the database with initial or testing data.
- Keep seeders organized by category (e.g.,
UsersTableSeeder,ProductsTableSeeder). - Use factories to create fake data for testing purposes.
By adhering to these standards, your developers will be able to create a robust, scalable, and secure database structure that supports your application's needs. Let me know if you need further details or additional guidelines!