LaravelLaravel21 min read

Foreign Keys and Constraints: Enforcing Data Integrity

Use foreign keys and cascading rules to prevent invalid data and reduce bugs.

Sophia Lane
October 23, 2025
2.9k121

Database constraints prevent invalid data, even if a developer makes a mistake in code.

    Example: A post must always belong to a valid user.
    
    ## Add foreign key in migration
    
    ```php
    Schema::create('posts', function (Blueprint $table) {
      $table->id();
      $table->foreignId('user_id')->constrained()->cascadeOnDelete();
      $table->string('title');
      $table->text('body');
      $table->timestamps();
    });
    ```
    
    This ensures:
    - user_id must exist in users table
    - if a user is deleted, their posts are deleted
    
    ## Graph: referential integrity
    
    ```mermaid
    flowchart LR
      A[users.id] --> B[posts.user_id]
      B --> C[DB Enforces Valid Link]
    ```
    
    In the next tutorial, we will build an audit trail using events and model observers.
#Laravel#Database#Advanced