1You may register the morphMap in the boot function of your
2App\Providers\AppServiceProvider class or create a separate service provider
3if you wish.
4
5use Illuminate\Database\Eloquent\Relations\Relation;
6
7Relation::morphMap([
8 'post' => 'App\Models\Post',
9 'video' => 'App\Models\Video',
10]);
1<?php
2
3namespace App\Models;
4
5use Illuminate\Database\Eloquent\Model;
6
7class Image extends Model
8{
9 /**
10 * Get the parent imageable model (user or post).
11 */
12 public function imageable()
13 {
14 return $this->morphTo();
15 }
16}
17
18class Post extends Model
19{
20 /**
21 * Get the post's image.
22 */
23 public function image()
24 {
25 return $this->morphOne(Image::class, 'imageable');
26 }
27}
28
29class User extends Model
30{
31 /**
32 * Get the user's image.
33 */
34 public function image()
35 {
36 return $this->morphOne(Image::class, 'imageable');
37 }
38}
1class Mechanic extends Model
2{
3 /**
4 * Get the car's owner.
5 */
6 public function carOwner()
7 {
8 return $this->hasOneThrough(
9 'App\Owner',
10 'App\Car',
11 'mechanic_id', // Foreign key on cars table...
12 'car_id', // Foreign key on owners table...
13 'id', // Local key on mechanics table...
14 'id' // Local key on cars table...
15 );
16 }
17}