Laravel 7.x Eloquent Relationships Example

In this tutorial i will discuss about laravel eloquent relationships example. In a relational database model, it’s expected that you will have tables that are related to each other. In this tutorial i will show you laravel eloquent one to many example. 

Eloquent provides simple and powerful tools to make the process of relating your database tables easier than using query builder. If you don't know how to use has many through relationship in laravel, then this tutorial is for you.

In an ORM like eloquent, you would call this a one-to-many relationship. Like the one company has many customer and the reverse is many customer has one company. 

So let's see how to create and use laravel one to many relationship example. 

laravel-model-relationships

And what if each contact has an address, but you’re only interested in tracking one address? You could have all the address fields on the Contact, but you might also create an Address model—meaning the contact has one address.

Read Also : Chaining with the Query Builder in Laravel

So, let’s dig into how to define and access these relationships. Let’s start simple: a Contact has one PhoneNumber. This relationship is defined in

Defining a one-to-one relationship

   class Contact extends Model
    {
        public function phoneNumber()
        {
            return $this->hasOne(PhoneNumber::class);
        }
    }

As you can tell, the methods defining relationships are on the Eloquent model itself ($this->hasOne()) and take, at least in this instance, the fully qualified class name of the class that you’re relating them to.

How should this be defined in your database? Since we’ve defined that the Contact has one PhoneNumber, Eloquent expects that the table supporting the PhoneNumber class (likely phone_numbers) has a contact_id column on it.

If you named it something different (for instance, owner_id), you’ll need to change your definition:

return $this->hasOne(PhoneNumber::class, 'owner_id');

Here’s how we access the phone number on a contact:

$contact = Contact::first();
$contactPhone = $contact->phoneNumber;

Notice that we define the method above with phoneNumber(), but we access it with ->phoneNumber. That’s the magic. You could also access it with
->phone_number. This will return a full Eloquent instance of the related PhoneNumber record.

But what if we want to access the Contact from the PhoneNumber? There’s a method for that, too

Defining a one-to-one relationship’s inverse

 class PhoneNumber extends Model
    {
        public function contact()
        {
            return $this->belongsTo(Contact::class);
        }
    }

Then we access it the same way:

$contact = $phoneNumber->contact;

Inserting related items

Each relationship type has its own quirks for how to relate models, but here’s the core of how it works: pass an instance to save(), or an array of instances to saveMany(). You can also pass properties to create() and it’ll make a new instance for you:

    $contact = Contact::first();

    $phoneNumber = new PhoneNumber;
    $phoneNumber->number = 8008675309;
    $contact->phoneNumbers()->save($phoneNumber);
    // or
    $contact->phoneNumbers()->saveMany([
        PhoneNumber::find(1),
        PhoneNumber::find(2),
    ]);
    // or
    $contact->phoneNumbers()->create([
        'number' => '+13138675309'
    ]);

Defining a has-many-through relationship

 class User extends Model
    {
        public function phoneNumbers()
        {
            return $this->hasManyThrough(PhoneNumber::class, Contact::class);
        }
    }

You’d access this relationship using $user->phone_numbers, and as always you can customize the relationship key on the intermediate model (with the third parameter of hasmanyThrough()) and the relationship key on the distant model (with the fourth parameter).

Many to many

This is where things start to get complex. Let’s take our example of a CRM that allows a User to have many Contacts, and each Contact to be related to multiple users. First, we define the relationship on the User as in below code

Defining a many-to-many relationship

 class User extends Model
    {
        public function contacts()
        {
            return $this->belongsToMany(Contact::class);
        }
    }

And since this is many to many, the inverse looks exactly the same 

Defining a many-to-many relationship’s inverse

    class Contact extends Model
    {
        public function users()
        {
            return $this->belongsToMany(User::class);
        }
    }

Hope it will help you. 

A web enthusiastic, self-motivated Full-Stack Web Developer from Dhaka, Bangladesh with experience in developing applications using JavaScript, Laravel & Wordpress specifically. Facebook Github Website