Relationships in PHP

From the Laravel cheat sheet · Eloquent ORM · verified Jul 2026

Relationships

Defining and using Eloquent relationships

php
// One to Many
class User extends Model
{
    public function posts()
    {
        return $this->hasMany(Post::class);
    }
}

class Post extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

// Usage
$user = User::find(1);
$posts = $user->posts;

$post = Post::find(1);
$author = $post->user;
💡 Use eager loading with() to prevent N+1 queries
⚡ Polymorphic relations allow a model to belong to multiple types
📌 Use withPivot() to access additional pivot table columns
🔥 whereHas() filters models based on relationship conditions

More PHP tasks

Back to the full Laravel cheat sheet