polymorphism laravel code example
Example 1: one to many laravel
For example, a blog post may have an infinite number of comments. And a single
comment belongs to only a single post
class Post extends Model
{
public function comments()
{
return $this->hasMany('App\Models\Comment');
}
}
class Comment extends Model
{
public function post()
{
return $this->belongsTo('App\Models\Post');
}
}
Example 2: laravel polymorphic model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Image extends Model
{
public function imageable()
{
return $this->morphTo();
}
}
class Post extends Model
{
public function image()
{
return $this->morphOne('App\Image', 'imageable');
}
}
class User extends Model
{
public function image()
{
return $this->morphOne('App\Image', 'imageable');
}
}
Example 3: morph relation laravel
You may register the morphMap in the boot function of your
App\Providers\AppServiceProvider class or create a separate service provider
if you wish.
use Illuminate\Database\Eloquent\Relations\Relation;
Relation::morphMap([
'post' => 'App\Models\Post',
'video' => 'App\Models\Video',
]);
Example 4: laravel poly morphic relationship
class Mechanic extends Model
{
public function carOwner()
{
return $this->hasOneThrough(
'App\Owner',
'App\Car',
'mechanic_id',
'car_id',
'id',
'id'
);
}
}