What is Eloquent?
Eloquent is Laravel's ORM โ Object Relational Mapper. It lets you interact with your database using PHP classes instead of writing raw SQL. Each database table gets its own Model class, and that class represents rows in the table.
If you've ever struggled with SQL queries, Eloquent will feel like a breath of fresh air. It's intuitive, readable, and powerful.
The Model Class
Every Eloquent model extends the base Model class. Here's a simple User model:
class User extends Model
{
//
}
By convention, the User model maps to the users table. Laravel handles the naming automatically. If you need a different table, set the $table property:
class User extends Model
{
protected $table = 'app_users';
}
Try it Yourself โ
Mass Assignment Protection
Mass assignment lets you create or update models by passing an array of attributes. But you need to protect against users injecting fields they shouldn't modify.
Use $fillable to whitelist attributes that can be mass-assigned:
class User extends Model
{
protected $fillable = ['name', 'email', 'password'];
}
Or use $guarded to blacklist specific attributes:
class User extends Model
{
protected $guarded = ['id', 'admin'];
}
Timestamps
Eloquent automatically manages created_at and updated_at columns. You don't need to set them โ Eloquent does it for you on every insert and update.
If your table doesn't have these columns, disable timestamps:
class User extends Model
{
public $timestamps = false;
}
Basic CRUD Operations
Creating, reading, updating, and deleting records with Eloquent is straightforward:
$user = new User;
$user->name = 'John';
$user->email = 'john@example.com';
$user->save();
Or create and save in one step:
$user = User::create([
'name' => 'John',
'email' => 'john@example.com',
]);
Retrieving records is just as simple:
$user = User::find(1);
$first = User::first();
$all = User::all();