when to use polymorphic relationship laravel code example
Example 1: 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 2: laravel polymorphic relationship why we need this relation orm,
$user->roles()->toggle([1, 2, 3]);
Example 3: laravel poly morphic relationship
class Mechanic extends Model
{
public function carOwner()
{
return $this->hasOneThrough(
'App\Owner',
'App\Car',
'mechanic_id',
'car_id',
'id',
'id'
);
}
}