Eloquent is Laravel's built-in ORM (Object-Relational Mapper). It allows you to interact with your database using PHP objects instead of writing raw SQL queries.
Laravel
Beginner
12 min read
Eloquent ORM
Example
// app/Models/Post.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model {
protected $fillable = ['title', 'body', 'user_id', 'published_at'];
protected $casts = ['published_at' => 'datetime'];
public function user() {
return $this->belongsTo(User::class);
}
public function tags() {
return $this->belongsToMany(Tag::class);
}
public function scopePublished($query) {
return $query->whereNotNull('published_at');
}
}
// Eloquent queries
$posts = Post::published()->latest()->paginate(10);
$post = Post::with('user', 'tags')->findOrFail($id);
$post = Post::create(['title' => 'Hello', 'body' => 'World', 'user_id' => 1]);
$post->update(['title' => 'Updated Title']);
$post->delete();
// Relationships
$user = User::find(1);
$posts = $user->posts()->where('published_at', '!=', null)->get();
echo $post->user->name;
Related Resources
Laravel Reference
Complete tag & property list
Laravel How-To Guides
Step-by-step practical guides
Laravel Exercises
Practice what you've learned
More in Laravel