SPONSORS

675 views · 1 months ago

![Laravel Eloquent Relationship Part 2](https:/ /images.ctfassets.net/vzl5fkwyme3u/3gY1sugUC3gTUtfgbhgNi5/410818aed6a8d4ea08e0ec796477291c/laravel_blog.png?w=1000)

As you all know, Laravel Eloquent Relationships are powerful and easy methods introduced by Laravel for helping developers to reduce the complexity when 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:

1. Has Many Through Relationship

2. One to Many Polymorphic

3. Many to many Polymorphic

## HAS MANY THROUGH ELOQUENT RELATIONSHIP

Has many through is a little bit complicated while understanding. I will provide a shortcut method to provide access data of another mode relationship. We will create a user table, post table, and country table and they will be interconnected with each other.

Here we will see Many through relationship will use `hasManyThrough()` for the 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 tweets and blogs, both having the comment system. So we need to add the comments. Then we can 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 too many relationships.

Now I will show one too many polymorphic will use `morphMany()` and `morphTo()` for 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 = Video::find(1);

$comment = new Comment;

$comment->body = "Hi Harikrishnan";

$video->comments()->save($comment);

```

Now we can retrieve records

```

$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 like every tweet and video will have multiple persons to tag. And for each and every tag there will be multiple tweet or videos.

Here we can understand the creating of many to many polymorphic relationships, 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 and etc..

Here `morphToMany()` and `morphedByMany()` will be used for many to many polymorphic relationships

### 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");

});

```

### 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 we can retrieve 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. In the above blog how has many through relationship, one to many polymorphic relationships and many to many polymorphic are working. This feature is introduced from Laravel 5.0 onwards and till the current version. Without the model, we can’t able to do this relationship. If we are using an eloquent relationship it will be very useful while developing an application.

SPONSORS