Skip to main content
Course/Module 11/Topic 2 of 4Advanced

Eloquent ORM & Database

Master Eloquent ORM — ActiveRecord pattern, relationships, query builder, migrations, and database optimization.

55 minBy Priygop TeamLast updated: Feb 2026

Eloquent ORM

  • Models: class User extends Model — each model maps to a database table. $fillable for mass assignment protection. $casts for automatic type conversion (JSON, datetime, boolean)
  • Relationships: hasOne, hasMany, belongsTo, belongsToMany — define relationships as methods. Eager loading: User::with('posts')->get() prevents N+1 query problem
  • Query Builder: DB::table('users')->where('active', true)->orderBy('name')->paginate(20) — fluent, type-safe query building. Raw expressions for complex SQL
  • Migrations: php artisan make:migration create_users_table — version-controlled schema changes. Up/down methods for rollback. Foreign keys, indexes, column modifications
  • Seeders & Factories: Factory pattern for generating test data — User::factory()->count(50)->create(). Seeders populate database with initial data. Faker for realistic fake data
  • Query Scopes: scopeActive($query) { return $query->where('active', true); } — reusable query conditions. User::active()->recent()->get(). Global scopes for automatic filters (soft deletes)
Chat on WhatsApp
Priygop - Leading Professional Development Platform | Expert Courses & Interview Prep