illuminate/database
Illuminate Database is Laravel’s standalone database toolkit for PHP: expressive query builder, Eloquent ORM (ActiveRecord), and schema builder. Supports MySQL, Postgres, SQL Server, and SQLite, and can be used via Capsule outside Laravel.
Start by installing the package via Composer (composer require illuminate/database) and setting up a Capsule instance to bootstrap database connectivity outside Laravel. The Capsule class is the easiest entry point—it abstracts away manual DI wiring. Initialize one connection (e.g., MySQL) with a simple array of config, then optionally enable Eloquent ORM with bootEloquent(). If you need Eloquent model events (like observers), also require illuminate/events. The first practical step: run a minimal query (Capsule::table('users')->get()) to confirm connectivity.
Use Capsule for lightweight standalone setups (e.g., CLI tools, microservices), while relying on Laravel’s built-in bindings (via app('db'), DB::, or Eloquent models) in full Laravel apps. Leverage the Query Builder for ad-hoc queries—especially when dynamic where clauses or joins are needed—and fall back to raw SQL only when necessary. Use Schema Builder for version-controlled DB changes—run migrations in php scripts via Schema::create() or Schema::table(). For business logic, favor Eloquent ORM models with relationships (hasMany, belongsTo), scopes, and accessors/mutators. Integrate logging via Laravel’s event system (if enabled) or hook into query events via DB::listen() for debugging. For transactions, prefer DB::transaction() for atomicity and automatic rollback.
Capsule instances don’t share connections—ensure you re-use or globalize the instance correctly.setAsGlobal() alone won’t enable ORM—bootEloquent() must be called after setting the event dispatcher.config/database.php loading) doesn’t happen—explicitly configure connections and options like charset and strict mode.select()/insert()—always use parameter binding (? placeholders or named bindings) to prevent SQL injection.Capsule and query builder are macroable, Eloquent models aren’t—extend via traits or observers instead.DB::enableQueryLog() in dev to inspect executed queries (but never in production—memory leak risk).Schema::drop('table') or dropIfExists() carefully—no automatic foreign key constraint checks unless manually configured per-DB.json or collection use SerializableClosure under the hood—ensure laravel/serializable-closure is installed if using closures in model attributes.How can I help you explore Laravel packages today?