🐘 PHP Intermediate

What is an ORM and how does Eloquent work?

Answer

An ORM (Object-Relational Mapper) maps database tables to PHP classes (models) and rows to objects, allowing you to interact with the database using PHP objects instead of writing raw SQL. Eloquent is Laravel's ORM. Define a model: class User extends Model { } — Eloquent automatically maps it to the users table. CRUD operations: User::find(1), User::create(["name" => "Alice"]), $user->update(["name" => "Bob"]), $user->delete(). Relationships are defined as methods: hasMany(), belongsTo(), belongsToMany(), hasOne(). Eloquent's fluent query builder: User::where("active", true)->orderBy("name")->paginate(20).