Laravel - Relationships - One To One Polymorphic Retrieving The Relationship
Once your database table and models are defined, you may access the relationships via your models. For example, to retrieve the image for a post, we can access the image
dynamic relationship property:
use App\Models\Post;
$post = Post::find(1);
$image = $post->image;
You may retrieve the parent of the polymorphic model by accessing the name of the method that performs the call to morphTo
. In this case, that is the imageable
method on the Image
model. So, we will access that method as a dynamic relationship property:
use App\Models\Image;
$image = Image::find(1);
$imageable = $image->imageable;
The imageable
relation on the Image
model will return either a Post
or User
instance, depending on which type of model owns the image.