<?phpuseIlluminate\Support\Facades\Route;useApp\Http\Controllers\TestController;/*|--------------------------------------------------------------------------| 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('/test/{id}', [TestController::class,'index']);Route::get('/test2/{id}', [TestController::class,'index2']);Route::get('/test3/{id}', [TestController::class,'index3']);Route::get('/test4/{id}', [TestController::class,'index4']);Route::get('/test5/{id}', [TestController::class,'index5']);
<?phpuseIlluminate\Database\Migrations\Migration;useIlluminate\Database\Schema\Blueprint;useIlluminate\Support\Facades\Schema;classCreateCommentsTableextendsMigration{/** * Run the migrations. * * @returnvoid */publicfunctionup() {Schema::create('comments',function (Blueprint $table) { $table->increments("id"); $table->string('body'); $table->integer('commentable_id'); $table->string('commentable_type'); }); }/** * Reverse the migrations. * * @returnvoid */publicfunctiondown() {Schema::dropIfExists('comments'); }}
C:\xampp\htdocs\songkhoe\app\Models\Post.php
<?phpnamespaceApp\Models;useIlluminate\Database\Eloquent\Factories\HasFactory;useIlluminate\Database\Eloquent\Model;classPostextendsModel{useHasFactory;public $timestamps =false;protected $fillable = ['title','body' ];/** * Get all of the post's comments. */publicfunctioncomments() {return$this->morphMany(Comment::class,'commentable'); }}
<?phpnamespaceApp\Models;useIlluminate\Database\Eloquent\Factories\HasFactory;useIlluminate\Database\Eloquent\Model;classVideoextendsModel{useHasFactory;public $timestamps =false;protected $fillable = ['title','url' ];/** * Get all of the video's comments. */publicfunctioncomments() {return$this->morphMany(Comment::class,'commentable'); }}
<?phpnamespaceApp\Models;useIlluminate\Database\Eloquent\Factories\HasFactory;useIlluminate\Database\Eloquent\Model;classCommentextendsModel{useHasFactory;public $timestamps =false;protected $fillable = ['body','commentable_id','commentable_type' ];/** * Get the parent commentable model (post or video). */publicfunctioncommentable() {return$this->morphTo(); }}
In this tutorial, one to many polymorphic laravel examples, I will explain what is polymorphic relationship and when we can use it in our laravel application. One to Many Polymorphic Model Relationships is used when a model belongs to more than one other model on a single association model. For example, If we have posts and videos tables, both need to add a comments system.
A one-to-many polymorphic relationship in laravel is similar to a one-to-many relation. However, if the child model can belong to more than one type of model using a single association then we can use this one-to-many polymorphic relationship in laravel.
In this laravel one to many polymorphic relationship tutorial, we can understand how to create migration with a foreign key schema for polymorphic one to many eloquent relationship, use sync with a pivot table, create records, get all data, delete, update and everything related to one to many polymorphic relationship.
One To Many (Polymorphic) Scenario
Taking the example mentioned above into consideration, we have two entities: Post and Video. To allow for comments on each of these, we can decide to set up our database like this:
posts id -integer title -string body - textvideos id -integer title -string url -stringcomments id -integer body - text commentable_id -integer commentable_type -string
PHPCopy
Model Structure of Polymorphic Relationship
Now let's define the one-to-many polymorphic relationship in our model class.
app/Models/Post.php
<?phpnamespaceApp\Models;useIlluminate\Database\Eloquent\Model;classPostextendsModel{/** * Get all of the post's comments. */publicfunctioncomments() {return$this->morphMany(Comment::class,'commentable'); }}
PHPCopy
Now define the relationship in the Video model like:
app/Models/Video.php
<?phpnamespaceApp\Models;useIlluminate\Database\Eloquent\Model;classVideoextendsModel{/** * Get all of the video's comments. */publicfunctioncomments() {return$this->morphMany(Comment::class,'commentable'); }}
PHPCopy
Now define the relationship in the Comment model like:
app/Models/Comment.php
<?phpnamespaceApp\Models;useIlluminate\Database\Eloquent\Model;classCommentextendsModel{/** * Get the parent commentable model (post or video). */publicfunctioncommentable() {return$this->morphTo(); }}
Once our database table and models are defined, we may access the relationships via your model's dynamic relationship properties. To access the comments for a Post, we can use the image a property declared in the model.
App\Http\Controllers\TestController.php
<?phpnamespaceApp\Http\Controllers;useApp\Models\Post;useIlluminate\Http\Request;classTestControllerextendsController{publicfunctionindex($id) { $post =Post::find($id);foreach ($post->comments as $comment) {// } }}
PHPCopy
For retrieving comments for a video:
App\Http\Controllers\TestController.php
<?phpnamespaceApp\Http\Controllers;useApp\Models\Video;useIlluminate\Http\Request;classTestControllerextendsController{publicfunctionindex($id) { $video =Video::find($id);foreach ($video->comments as $comment) {// } }}
PHPCopy
Save Polymorphic Relationship Data
If we want to save or create polymorphic relationship data then we can follow the below structure:
We have tried to discuss the basic concept of one to many polymorphic relationships and their possible use cases in laravel applications. We should also note that one to many polymorphic relationships are not a perfect solution to everything and should only be used when convenient or feels like the right way to go.