Laravel One To Many Polymorphic Eloquent Relationship Tutorial Example – onlinecode

Laravel One To Many Polymorphic Eloquent Relationship Tutorial Example – onlinecode

In this post we will give you information about Laravel One To Many Polymorphic Eloquent Relationship Tutorial Example – onlinecode. Hear we will give you detail about Laravel One To Many Polymorphic Eloquent Relationship Tutorial Example – onlinecodeAnd how to use it also give you demo for it if it is necessary.

In this tutorial, today we discuss about laravel many to many Eloquent relationship. Eloquent ORM means Object-relational Mapping and laravel provides a beautiful activerecord stucture. so we can easy to interact with application database. let’s start about One To Many Polymorphic eloquent relationship.

A one-to-many polymorphic relation is similar to a one to one eloquent relationship. but, the target model can belong to more than one type of model on a single association. For example, suppose we have posts and videos table. users can “comment” on both posts and videos.

here, see below database stucture.

posts

– id

– name

videos

– id

– name

comments

– id

– commentable_id

– commentable_type

Setting Database Configuration

After complete installation of laravel. we have to database configuration. now we will open the .env file and change the database name, username, password in the .env file. See below changes in a .env file.

PHP
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=Enter_Your_Database_Name(one_many_polymorphic_relation)
DB_USERNAME=Enter_Your_Database_Username(root)
DB_PASSWORD=Enter_Your_Database_Password(root)

Create Table using migration

Now, We need to create a migration. so we will below command using create the posts and images table migration.

PHP
php artisan make:migration create_posts_table --create=posts
php artisan make:migration create_videos_table --create=videos
php artisan make:migration create_comments_table --create=comments

After complete migration. we need below changes in the database/migrations/create_posts_table, database/migrations/create_videos_table and database/migrations/create_comments_table file.

create_posts_table.php

PHP
<?php
use IlluminateSupportFacadesSchema;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;
class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}
?>

create_videos_table .php

PHP
<?php
use IlluminateSupportFacadesSchema;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;
class CreateVideosTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('videos', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('videos');
    }
}
?>

create_comments_table .php

PHP
<?php
use IlluminateSupportFacadesSchema;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;
class CreateCommentsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('comments', function (Blueprint $table) {
            $table->bigIncrements('id');
			$table->integer('commentable_id');
            $table->string("commentable_type");
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('comments');
    }
}
?>

Run the below command. after the changes above file.

PHP
php artisan migrate

Create Model

Here below command help through we will create the Post, Video and Comment model. we will also use “morphMany()” function for Post and Video model.

PHP
php artisan make:model Post
php artisan make:model Video
php artisan make:model Comment

Post.php

PHP
<?php
namespace App;
use IlluminateDatabaseEloquentModel;
class Post extends Model
{
    public function comments()
    {
        return $this->morphMany(Comment::class, 'commentable');
    }
}
?>

Video.php

PHP
<?php
 
namespace App;
 
use IlluminateDatabaseEloquentModel;
 
class Video extends Model
{
    public function comments()
    {
        return $this->morphMany(Comment::class, 'commentable');
    }
}

?>

Comment.php

PHP
<?php
 
namespace App;
 
use IlluminateDatabaseEloquentModel;
 
class Comment extends Model
{
    public function commentable()
    {
        return $this->morphTo();
    }
}

?>

Route and Controller

We have to need put below code route in routes/web.

PHP
<?php
 
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
 
Route::get('/', function () {
    return view('welcome');
});
 
Route::get('post','postsController@index');

?>

Here below command help to create the post controller.

PHP
php artisan make:controller PostsController

PostsController.php

PHP
<?php
namespace AppHttpControllers;
use AppPost;
use AppVideo;
use AppComment;
use IlluminateHttpRequest;
class PostsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return IlluminateHttpResponse
     */
    public function index()
    {
		
	   $post = Post::find(1);
       $post_comment = $post->comments;
       //dd($post_comment);	
 
       $video = Video::find(1);
       $video_comment = $video->comments;
	   //dd($video_comment);	
    }

}
?>

Please follow and like us:

Hope this code and post will helped you for implement Laravel One To Many Polymorphic Eloquent Relationship Tutorial Example – onlinecode. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

Leave a Comment

Your email address will not be published. Required fields are marked *

4  +  5  =  

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US