At Agira, Technology Simplified, Innovation Delivered, and Empowering Business is what we are passionate about. We always strive to build solutions that boost your productivity.

,

Laravel Eloquent Relationships – Part 2

  • By Harikrishnan R
  • September 10, 2018
  • 946 Views

In our previous blogs, we had clearly discussed about the Laravel eloquent relationships and i also addressed you guys that i will continue this topic in part 2. So as i promised, here am releasing you the another part of Laravel Eloquent Relationship and this time, we’re bit close to cover all the concept of Laravel Eloquent relationships.
As you all know laravel eloquent relationships are powerful and easy method introduced by laravel for helping developers to reduce the complexity of connecting with multiple tables. While connecting with multiple tables, this method is very easy for developers for creating the application.
Here you can see the next three methods of the eloquent relationships.

  • Has Many Through Relationship
  • One to Many Polymorphic
  • Many to many Polymorphic

 

Has Many Through Eloquent Relationship

Has many through is bit complicated to understand so am providing a shortcut method to access data of another mode relationship. Therefore, we can able to create users table, post table, and countries table and they will be interconnected with each other.
Here we will see Many through relationship will use “hasManyThrough()”in relation

Create Migrations

 

Users Table

 

Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->integer('country_id')->unsigned();
$table->rememberToken();
$table->timestamps();
$table->foreign('country_id')->references('id')->on('countries')
->onDelete('cascade');
});

 

Posts Table

 

Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string("name");
$table->integer('user_id')->unsigned();
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')
->onDelete('cascade');
});

Countries Table

 

Schema::create('countries', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->timestamps();
});

Create Models

 

Country Model

 

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Country extends Model
{
    public function posts()
    {
        return $this->hasManyThrough(
            Post::class,
            User::class,
            'country_id', // Foreign key on users table...
            'user_id', // Foreign key on posts table...
            'id', // Local key on countries table...
            'id' // Local key on users table...
        );
    }
}

Now we can retrieve records by

$country = Country::find(1);
dd($country->posts);

 

One To Many Polymorphic Relationship

One to many polymorphic relationships used one model belongs to another model on a single file. For example, we will have tweet and blogs, both having a comment system. So we need to add the comments. Then we can get to manage both in a single table.
Here we will use sync with a pivot table, create records, get all data, delete, update and everything related to one to many relationships.
Now I will show one to many polymorphic for that we need to use “morphMany()” and “morphTo()”in relation.

Create Migrations

 

Posts Table

 

Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string("name");
$table->timestamps();
});

 

Videos Table

 

Schema::create('videos', function (Blueprint $table) {
$table->increments('id');
$table->string("name");
$table->timestamps();
});

 

Comments Table

 

Schema::create('comments', function (Blueprint $table) {
$table->increments('id');
$table->string("body");
$table->integer('commentable_id');
$table->string("commentable_type");
$table->timestamps();
});

 

Create Models

Post Model

 

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
/**
* Get all of the post's comments.
*/
public function comments()
{
return $this->morphMany(Comment::class, 'commentable');
}
}

 

Video Model

 

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Video extends Model
{
/**
* Get all of the post's comments.
*/
public function comments()
{
return $this->morphMany(Comment::class, 'commentable');
}
}

 

Comment Model

 

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
/**
* Get all of the owning commentable models.
*/
public function commentable()
{
return $this->morphTo();
}
}

 

Create Records

 

$post = Post::find(1);
$comment = new Comment;
$comment->body = "Hi Harikrishnan";
$post->comments()->save($comment);
$video = Video::find(1);
$comment = new Comment;
$comment->body = "Hi Harikrishnan";
$video->comments()->save($comment);

You could see the retrieved records like below,

$post = Post::find(1);
dd($post->comments);
$video = Video::find(1);
dd($video->comments);

 

Many To Many Polymorphic Relationships

Many to many polymorphic is also a little bit complicated like above. If we have a tweet, video and tag table, we need to connect each table but every tweet and video will have multiple persons to tag. Also, for each and every tag there will be multiple tweet or videos. So how we can connect each other and maintain the relationship for each?
Now you can understand the concept of creating many to many polymorphic relationships here, with a foreign key schema of one to many relationships, use sync with a pivot table, create records, attach records, get all records, delete, update, where condition, etc.
Here “morphToMany()” and “morphedByMany()” will be used for many to many polymorphic relationships

Also Read: Generate Charts And Graphs Using Laravel

Creating Migrations

Posts Table

 

Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string("name");
$table->timestamps();
});

 

Videos Table

 

Schema::create('videos', function (Blueprint $table) {
$table->increments('id');
$table->string("name");
$table->timestamps();
});

 

Tags Table

 

Schema::create('tags', function (Blueprint $table) {
$table->increments('id');
$table->string("name");
$table->timestamps();
});

 

Taggables Table

 

Schema::create('taggables', function (Blueprint $table) {
$table->integer("tag_id");
$table->integer("taggable_id");
$table->string("taggable_type");
});

 

Tips: How To Embed The JW Player Into Website

 

Creating Models

 

Post Model

 

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
/**
* Get all of the tags for the post.
*/
public function tags()
{
return $this->morphToMany(Tag::class, 'taggable');
}
}

 

Video Model

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Video extends Model
{
/**
* Get all of the tags for the post.
*/
public function tags()
{
return $this->morphToMany(Tag::class, 'taggable');
}
}

 

Tag Model

 

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Tag extends Model
{
/**
* Get all of the posts that are assigned this tag.
*/
public function posts()
{
return $this->morphedByMany(Post::class, 'taggable');
}
/**
* Get all of the videos that are assigned this tag.
*/
public function videos()
{
return $this->morphedByMany(Video::class, 'taggable');
}
}

 

Creating Records

 

$post = Post::find(1);
$tag = new Tag;
$tag->name = "Hi Harikrishnan";
$post->tags()->save($tag);
$video = Video::find(1);
$tag = new Tag;
$tag->name = "Vishnu";
$video->tags()->save($tag);
$post = Post::find(1);
$tag1 = new Tag;
$tag1->name = "Kerala Blasters";
$tag2 = new Tag;
$tag2->name = "Manajapadda";
$post->tags()->saveMany([$tag1, $tag2]);
$video = Video::find(1);
$tag1 = new Tag;
$tag1->name = "Kerala Blasters";
$tag2 = new Tag;
$tag2->name = "Manajappada";
$video->tags()->saveMany([$tag1, $tag2]);
$post = Post::find(1);
$tag1 = Tag::find(3);
$tag2 = Tag::find(4);
$post->tags()->attach([$tag1->id, $tag2->id]);
$video = Video::find(1);
$tag1 = Tag::find(3);
$tag2 = Tag::find(4);
$video->tags()->attach([$tag1->id, $tag2->id]);
$post = Post::find(1);
$tag1 = Tag::find(3);
$tag2 = Tag::find(4);
$post->tags()->sync([$tag1->id, $tag2->id]);
$video = Video::find(1);
$tag1 = Tag::find(3);
$tag2 = Tag::find(4);
$video->tags()->sync([$tag1->id, $tag2->id]);

Now you can see the retrieved records,

$post = Post::find(1);
dd($post->tags);
$video = Video::find(1);
dd($video->tags)
$tag = Tag::find(1);
dd($tag->posts);
$tag = Tag::find(1);
dd($tag->videos);

Hence we completed all the relationships. this feature is introduced from laravel 5.0 onwards and till the current version. Without a model, we can’t able to do this relationship. If we are using eloquent relationship, it will be very useful while developing an application.
Hope this helps you! and if you also wish to explore more about technologies then join us on the excursion of exploring Technologies subscribe us to get more blogs & updates on latest technologies. Agira Technologies one of the fastest growing Web and Mobile Development Company in India. Precisely, extends its research on Web technologies, Mobile Apps, Blockchain, Chatbot, Artificial Intelligence, iOT and lot more. Explore more about us on www.agiratech.com.
For any inquiries reach us at info@agiratech.com

Harikrishnan R

Around 3 years of experience he scored intense knowledge on PHP, Laravel, Symfony, Angular & ensuring to learn the new & best methods to bring excellence in building applications. Also he has some aspiring dream to do Doctorate and the strange reason behind this will definitely leave a smile on your face! Yeah because he just loves writing his name as Dr. Harikrishnan