Field Manual PHP / Laravel reference
← SQL

Foreign keys

Foreign keys require referenced records to exist.

What it is

Foreign keys require referenced records to exist.

When to use it

Enforce ownership relationships and deletion rules.

Syntax

user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE RESTRICT

Example

PRAGMA foreign_keys = ON; -- SQLite: per connection
CREATE TABLE audit_logs (
    id INTEGER PRIMARY KEY,
    actor_id INTEGER REFERENCES users(id) ON DELETE RESTRICT,
    action TEXT NOT NULL,
    subject_id INTEGER NOT NULL,
    created_at TEXT NOT NULL
);

Common mistakes

SQLite enforcement must be enabled; nullable actor may be appropriate for system actions.

Related topics

Browse SQL