Laravel

Laravel Eloquent Relationships with Example

January 30, 2018

author:

Laravel Eloquent Relationships with Example

Database tables are usually interrelated. For instance, a blog post may have multiple tags. In any application, database relationships can get as simple or as complicated as one can imagine it. Eloquent in Laravel 5.6 makes working and managing with such relationships a lot easier and readable. It also supports various types of relationships:

• One to One
• One to Many
• Many to Many
• Has Many Through
• Polymorphic Relations
• Many to Many Polymorphic Relations

# Defining Eloquent Relationships in Laravel 5.6

We can define Eloquent relationships as methods in the subsequent Eloquent model classes. As a result of this feature, relationships can also be used as a method for query builders. We will talk about this later in this series, now, let us work with some commonly used relationships.

# One to One Relationship with Example

The one to one relationship is one of the basic relations. For instance, a User model would be associated with one profile. To depict this relationship, we can create a profile() method within the User model and call hasOne() method to relate Profile model.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    public function profile()
    {
        return $this->hasOne('App\Profile');
    }
}

It is important to note that Eloquent establishes foreign key based on the model name and should have a matching value id. For instance, Profile model is assumed to have a user_id foreign key. Taking a step deeper, if Profile is tied with Avatar Model on a hasOne relationship, then Avatar model is expected to have a profile_id foreign key.

We can now access the user – profile relation with a dynamic method like this:

$profile = User::find(8)->profile;

Defining the Inverse One to One Relationship:

Up till now, we can access Profile from the User. Now let us create an inverse relationship on the Profile model so as to access User model from it. To do so, we can use the belongsTo method. As in – a Profile belongs to a user.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Profile extends Model
{
    public function user()
    {
        return $this->belongsTo('App\User');
    }
}

In the above example, as discussed earlier, Eloquent will try and match the user_id from Profile method to an id on the User model. That is, it defines the default foreign key name by detecting the name of the relationship method and suffixing it with _id. Eloquent does this for all the relationships, so please understand and keep this tweak in mind. Hope that clears the ambiguity once and for all.

# One to Many Relationship with Example

The one to many relationship determines a relationship where a single model owns n number of other model. For instance, a User can have an infinite number of photos. As one to one relationship, many to many relationship is also defined within the corresponding models and Eloquent automatically determines a foreign key user_id in Photo model.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    ...
    public function photos()
    {
        return $this->hasMany('App\Photo');
    }
}

We can then access the collection of photos by using the photos() method as:

$photos= App\User::find(24)->photos()->where('tag', 'candid')->get();

foreach ($photos as $photo) {
    //do something
}

Defining the Inverse One to Many Relationship:

Since we can now access all the photos of a user, it is time to allow a photo to access its parent model, i.e., User. The inverse relationship of both One to One and One to Many works the same way. Both use belongTo method to define the inverse relation. Thus we can define one as:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Photo extends Model
{
    public function user()
    {
        return $this->belongsTo('App\User');
    }
}

# Many to Many Relationship with Example

The many to many relationship may look tricky in the beginning, but once you understand the basics, it would sound obvious to you. For instance, n number of users can posses the role ‘Customer’. To define this type of relationship, we need three tables – users, roles and role_user. The only catch to understand here is that the role_user is derived from an alphabetic order of its related model names (i.e., role and order). The role_user must also contain user_id and role_id columns.

To define many to many relationship, we use belongsToMany() method.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
   ...
    public function roles()
    {
        return $this->belongsToMany('App\Role');
    }
}

We can now access the roles with dynamic method:

$user = App\User::find(8);

foreach ($user->roles as $role) {
   //do something
}

Defining the Inverse Many to Many Relationship:

The inverse of a many to many relationship can be defined by simply calling the similar belongsToMany method on the reverse model. We can illustrate that by defining user() method in Role model as:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    public function users()
    {
        return $this->belongsToMany('App\User');
    }
}

Conclusion:
The three relationships one to one, one to many and many to many relationship that we just saw are some the basic relationship components of any applications. At times, even the complex projects, the relationship between multiple tables can be defined with just these three concepts. Though they are three other relationships not covered here, the chances of using them are really thin and hence we are not covering them for now and maybe will see on later stage.

Questions & Comments:

Thank you for reading. If you face any difficulty while working with relationships in Laravel, share them in the comment section below.

Leave a comment

Your email address will not be published. Required fields are marked *