Eloquent Relationships in Laravel.


In Laravel, Eloquent is the default ORM (Object-Relational Mapping) included with the framework. It provides a simple and expressive way to interact with your database tables using PHP objects. One of the key features of Eloquent is its support for defining and working with relationships between database tables.

Eloquent relationships allow you to define the connections between your database tables using object-oriented syntax, making it easy to retrieve and manipulate related data. There are several types of relationships available in Laravel Eloquent:

  1. One-to-One Relationship: This relationship defines that each record in one table has a corresponding record in another table. For example, a User has one Profile.
  2. One-to-Many Relationship: In this relationship, a single record in one table can be associated with multiple records in another table. For example, a User has many Posts.
  3. Many-to-Many Relationship: This relationship allows multiple records in one table to be associated with multiple records in another table. For example, a User can have multiple Roles, and a Role can belong to multiple Users.
  4. Has-One-Through and Has-Many-Through: These relationships define a way to access distant related models. For example, a Country has one Through a User’s Profile.

To define relationships in Laravel, you can use Eloquent’s methods and conventions. For example, to define a one-to-many relationship between the User and Post models, you would add the following methods to the respective models:

class User extends Model
    public function posts()
        return $this->hasMany(Post::class);

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

With these relationship methods in place, you can easily access related data. For example, to retrieve all posts belonging to a user, you can use:

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

Laravel’s Eloquent relationships provide a powerful and intuitive way to work with related data in your application. They help simplify complex database queries and make it easy to retrieve and manipulate data across multiple tables. By leveraging these relationships, you can create more efficient and maintainable code when working with databases in Laravel.

Reference document from Laravel official documentation.