All Eloquent ORM lessons

Relationships

7 min read

Eloquent models a relationship as a method that returns a relation object.

// One user has many posts
class User extends Model {
    public function posts() { return $this->hasMany(Post::class); }
}
class Post extends Model {
    public function author() { return $this->belongsTo(User::class, 'user_id'); }
}
Relationship Where's the FK? Example
hasOne On the related model User → Profile
hasMany On the related model User → posts
belongsTo On this model Post → author (user_id)
belongsToMany In a pivot table Post ↔ Tag (post_tag)
morphTo A column + a type column Comment → commentable

Using a relationship

$user->posts;                          // collection of Post
$user->posts()->where('is_published', true)->get();
$user->posts()->create(['title' => 'New']); // creates with user_id set
$post->author->name;                   // uses inverse

Constraining at fetch time

User::withCount('posts')->withMax('posts', 'created_at')->get();

withCount, withSum, withMax, withMin, withAvg all add aggregated columns without joining.