Backend Development
Laravel
Subjective
Sep 30, 2025
Explain Eloquent relationships with code examples.
Detailed Explanation
Eloquent provides several relationship types:
**One-to-One:**
class User extends Model {
public function profile() {
return $this->hasOne(Profile::class);
}
}
class Profile extends Model {
public function user() {
return $this->belongsTo(User::class);
}
}
**One-to-Many:**
class Post extends Model {
public function comments() {
return $this->hasMany(Comment::class);
}
}
class Comment extends Model {
public function post() {
return $this->belongsTo(Post::class);
}
}
**Many-to-Many:**
class User extends Model {
public function roles() {
return $this->belongsToMany(Role::class);
}
}Discussion (0)
No comments yet. Be the first to share your thoughts!
Share Your Thoughts