22 | Laravel For Starters ~ Eloquent: Relationships Overview | by ismail | Oct, 2024
In Laravel, Eloquent ORM (Object-Relational Mapping) simplifies working with database relationships through an intuitive, expressive syntax. Relationships in Eloquent allow you to associate models and access related data effortlessly. This article covers the different types of relationships available in Eloquent, providing code examples and explaining how to set up these relationships to make the most of your Laravel projects.
A one-to-one relationship is a relationship where each instance of a model is associated with a single instance of another model. For example, a User
model might have one Profile
.
Defining a One-to-One Relationship:
In the User
model:
// User.php
public function profile()
{
return $this->hasOne(Profile::class);
}
In the Profile
model:
// Profile.php
public function user()
{
return $this->belongsTo(User::class);
}
Usage Example: To access a user’s profile:
$user = User::find(1);
$profile = $user->profile;
To access the user from the profile:
$profile = Profile::find(1);
$user = $profile->user;