Top
eloquent relationship in Laravel Development

Eloquent Relationships in Laravel Development

In today’s era of fast paced development, writing direct SQL queries can be pretty time consuming and tedious for a developer. Although writing raw queries has its own advantages but sanitization of requests and writing prepared statement can be very much cumbersome. So in order to solve these problem Laravel Development comes with a pretty handy solution and i.e Eloquent ORM.

Before getting into Eloquent we must first understand what is an ORM ?

ORM or Object-relational mapping According to wikipedia  “Orm in computer science is a programming technique for converting data between incompatible type systems using object-oriented programming languages. This creates, in effect, a “virtual object database” that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping.”

Now, Eloquent is a Laravel Development implementation of an ORM. It provides a very beautiful and simple Active Record Implementation.This Implementation actually helps in reducing the code and start more reusing of your code and helps a developer in  using DRY principles (Do Not Repeat Yourself).This not only reduces your code but also makes the code much more readable. In Eloquent each Database tables are represented as a model class in your code base and each column in your table is represented as member of that class. So that we can play with the data in our database make awesome applications with dynamic data.

Let us now understand how does eloquent makes our lives easier with an example:

I believe everyone will agree with me that anyone who wants to make an application it will definitely serve some kind of users. So in our example we will have a user and they will post something on our application. Now these two entities will be represented in our database with 2 tables, first user table and another is post table. If these are 2 tables in our database then this will be represented as two models in our code base one user and another as post table. Now if we want to fetch a record of all the post of user 1.

Consideration:

user_id is the foreign key in the posts table

Raw SQL:

Select * from posts join users on posts.user_id = users.id where users.id = 1

Eloquent Approach:

User::find(1)->posts()

The above mentioned example is just a basic example of how much easy it is to write it in eloquent approach.

Now after all this let us dive into Laravel’s mapping functionalities ,Eloquent supports many kinds of mapping following is the list of mappings

Laravel Development Mappings:

  • One To One
  • One To Many
  • Many To Many

One To One

The one-to-one relationship is a very common relation. For example, a Parent model which comes associated with one Child. To explain this relationship, we put a child method on the Parent model. The child method should call the hasOne method and return its result:

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Parent extends Model
{

   public function child()
    {
        return $this->hasOne('App\Child’);
    }
}

Defining The Inverse Of The Relationship

So, we can drive the Parent model from our Child. Now, let’s explain a relationship on the Child model that will let us drive the Parent that owns the device. We can define the inverse of a hasOne relationship using the belongsTo method:

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Child extends Model{
    public function parent()
    {
        return $this->belongsTo('App\Parent’)

     }
}

One To Many

A single User can have multiple number of post. Like all other Eloquent relationships, one-to-many relationships are defined by putting a function on your Eloquent model.

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
    public function posts()
    {
        return $this->hasMany('App\Post);
    }
}

***Note***

Eloquent will consider the “snake case” name of owning a model and suffix it with _id. So, for this example, Eloquent will assume the foreign key on the Post model is user_id. This is basically a naming convention for laravel development models but that doesnt mean Eloquent does not support other names for your foreign key. For detail description you can find it in the docs.

One To Many (Inverse)

Now that we can use all of a users posts, let’s explain a relationship to allow a post to use its parent user. To define the inverse of a hasMany relationship, explain a relationship function on the child model which calls the belongsTo method:

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model{
    public function user()
    {
        return $this->belongsTo('App\User’);
    }
}

Many To Many

This type of relationships are little more complicated than one to one or one to many
Relationships. Here let us take into considerations Products ,Sizes and Product prices in accordance to their sizes. So there will be three tables in our data base products, sizes, product_size. So in order to create the relationship between these model let us look at the models.

Many-to-many relationships are defined by writing a method that returns the result of the belongsToMany method.

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model{
    public function size()
    {
        return $this->belongsToMany('App\Size’);
    }
}

Many To Many (Inverse)

To define the inverse of a many-to-many relationship, you place another call to belongsToMany on your related model. So for example let us checkout the size model.

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Size extends Model{
    public function size()
    {
        return $this->belongsToMany('App\Product’);
    }
}

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Size extends Model{
    public function product()
    {
        return $this->belongsToMany('App\Product);
    }
}

Laravel supports many other Eloquent relationships like Has Many Through , Polymorphic Relation, Many To Many Polymorphic Relations we have gone through three Eloquent relationships in this blog just to give the flavour of how Eloquent relationships works and how much rapid laravel development supports. Hope that this article was helpful.

Saptarshi Banerjee

Saptarshi have been working with Laravel for the past three years . He came from B.Tech(CSE) background. He also like to learn new programming language currently complilng Python ….