Laravel

Laravel Eloquent: Advanced Relationships

December 24, 2025 1 min read 17 views

Master advanced Eloquent relationships:

Has One Through

public function latestPost()
{
    return $this->hasOneThrough(Post::class, Author::class)->latest();
}

Many to Many with Pivot Data

$user->roles()->attach($roleId, ['expires_at' => now()->addYear()]);

Polymorphic Relationships

public function commentable()
{
    return $this->morphTo();
}

These relationships handle complex data structures elegantly.

Share this post:

Related Posts

Comments (0)

Please log in to leave a comment. Log in

No comments yet. Be the first to comment!