Eloquent Relationships In Laravel Development

Swarnendu De September 27, 2018

Updated on ‘Aug 13, 2019

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 statements can be quite cumbersome. So in order to solve these problems, Laravel Development comes with a pretty handy solution and i.e Eloquent ORM.

Before Getting Into Eloquent, We Must 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 codebase and each column in your table is represented as a member of that class. So that we can play with the data in our database to make awesome applications with dynamic data.

Related read: Top 10 Laravel Best Practices You Should Follow

Let us now understand how 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

laravel development

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’)     } }

Related read: Top 10 Website Development Best Practices for Newbies & Pro

One To Many

A single user can have multiple numbers 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 doesn’t mean Eloquent does not support other names for your foreign key. For a detailed description, you can find it in the docs.

laravel development

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’);
    }
}

Related read:Where is Responsive Web Design Headed?

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 database 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’);    } }

Related read: Progressive Web Apps – 5 Proven Reasons Your Business Needs It Now!

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 check out 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);    } }

To Sum This Up For You…

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 flavor of how Eloquent relationships works and how much rapid larval development supports. Hope that this article was helpful.

Using the Laravel best practices for creating web apps for since it’s launch, we have worked with startups and entrepreneurs big and small. We understand the pain a customer goes through in order to find the development company right for their project. Which is why, we take extra care to serve and fulfill your needs with our unique approach. Talk to us about your requirements today!

laravel development

This post was originally published on Sep 27, 2018 and has been updated for accuracy and comprehensiveness.