Skip to content
  • About Us
  • Contact Us
  • Privacy Policy
  • Terms & Conditions
  • Site Map

XpertPhp

Expertphp Is The Best Tutorial For Beginners

  • Home
  • Javascript
    • Jquery
    • React JS
    • Angularjs
    • Angular
    • Nodejs
  • Codeigniter
  • Laravel
  • Contact Us
  • About Us
  • Live Demos

Laravel One To Many Polymorphic Eloquent Relationship Tutorial Example

Posted on October 30, 2019January 25, 2021 By XpertPhp 2 Comments on Laravel One To Many Polymorphic Eloquent Relationship Tutorial Example

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
1
2
3
4
5
6
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
1
2
3
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
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
1
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
1
2
3
php artisan make:model Post
php artisan make:model Video
php artisan make:model Comment

Post.php

PHP
1
2
3
4
5
6
7
8
9
10
11
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
    public function comments()
    {
        return $this->morphMany(Comment::class, 'commentable');
    }
}
?>

Video.php

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Video extends Model
{
    public function comments()
    {
        return $this->morphMany(Comment::class, 'commentable');
    }
}
 
?>

Comment.php

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?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','[email protected]');
 
?>

Here below command help to create the post controller.

PHP
1
php artisan make:controller PostsController

PostsController.php

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?php
namespace App\Http\Controllers;
use App\Post;
use App\Video;
use App\Comment;
use Illuminate\Http\Request;
class PostsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    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:
error
fb-share-icon
Tweet
fb-share-icon

Recommended Posts:

  • Laravel 8 Cron Job Scheduling Example Tutorial
  • Laravel 8 Pdf Generator Tutorial Using Dompdf
  • Laravel 8 Google Pie Chart Example From Scratch
  • Laravel 9 Integrate Ckeditor With Example
  • laravel eloquent Union query example
Laravel, MySql Tags:eloquent relationships, laravel 6, Laravel 6 Eloquent, laravel 6 relationship, laravel 6 relationship eloquent

Post navigation

Previous Post: Laravel hasManyThrough eloquent relationship tutorial example
Next Post: Laravel One To One Polymorphic Eloquent Relationship Tutorial Example

Categories

  • Ajax
  • Angular
  • Angularjs
  • Bootstrap
  • Codeigniter
  • Css
  • Htaccess
  • Javascript
  • Jquery
  • Laravel
  • MongoDB
  • MySql
  • Nodejs
  • Php
  • React JS
  • Shopify Api
  • Ubuntu

Tags

angular 10 tutorial angular 11 ci tutorial codeigniter 4 image upload Codeigniter 4 Tutorial codeigniter tutorial CodeIgniter tutorial for beginners codeigniter with mysql crud operation eloquent relationships file upload File Validation form validation Image Upload jQuery Ajax Form Handling jquery tricks jquery tutorial laravel 6 Laravel 6 Eloquent Laravel 6 Model laravel 6 relationship laravel 6 relationship eloquent Laravel 6 Routing laravel 7 Laravel 7 Eloquent laravel 7 routing laravel 7 tutorial Laravel 8 laravel 8 example laravel 8 tutorial laravel 9 example laravel 9 tutorial Laravel Framework laravel from scratch Laravel Socialite laravel social login nodejs pagination payment gateway php with mysql react js tutorial rewrite rule send mail validation wysiwyg editor

Latest Posts

  • How to Convert Date and Time from one timezone to another in php
  • how to get current date and time in php
  • Drag and Drop Reorder Items with jQuery, PHP & MySQL
  • Laravel 9 Toastr Notifications Example Tutorial
  • Laravel 9 CRUD Operation Example Using Google Firebase
  • Laravel 9 CKeditor Image Upload With Example
  • Laravel 9 Summernote Image Upload With Example
  • Laravel 9 Stripe Payment Gateway Integrate Example
  • How To Send Email Using Mailtrap In Laravel 9
  • Laravel 9 Fullcalendar Ajax Example Tutorial

Tools

  • Compound Interest Calculator
  • Hex to RGB Color Converter
  • Pinterest Video Downloader
  • Age Calculator Online
  • Convert JSON to PHP Array Online
  • JavaScript Minifier
  • CSS Beautifier
  • CSS Minifier
  • JSON Beautifier
  • JSON Minifier

Copyright © 2018 - 2022,

All Rights Reserved Powered by XpertPhp.com