user123
user123

Reputation: 267

Trying to call the relationship of imageable_type in polymorphic model

So I have images that are stored by a particular model each time they recorded (i.e. Thread, Reply, Comment).

I want to call to be able to call these values to get the path where the images originate from.

So far I have this code:

In each of the models (Thread, Reply, Comment):

public function images()
{
    return $this->morphMany(Image::class, 'imageable');
}

In the Image Model:

public function image()
{
    return $this->morphTo();
}

In the view (I can't figure out how to call the related model here)

<div class="image-show">
    Found here: 
    @if ($image->imageable_type == 'App\Thread')
    <a href="/forums/{{ $image->image->channel->slug }}/{{ $image->image->slug }}/">
        {{ $image->image->title }}
    </a>
    @endif
    @if ($image->imageable_type == 'App\Reply')
    <a href="">
        {{ dd($image->image()->path()) }}
    </a>
    @endif
    @if ($image->imageable_type == 'App\ProfilePost')
    <a href="{{ $image->path() }}">{{ $image->image->user->name }}'s profile
    </a>
    @endif
    @if ($image->imageable_type == 'App\ProfilePostComment')
    @endif
    @if ($image->imageable_type == 'App\Product')
    @endif
    @if ($image->imageable_type == 'App\Review')
    @endif
    @if ($image->imageable_type == 'App\ReviewComment')
    @endif
    @if ($image->imageable_type == 'App\Thread')
    @endif
    @if ($image->imageable_type == 'App\ProductComment')
    @endif
    <img src="{{ $image->path }}">
</div>

Can anyone help show me how I can call the imageable_type relationship to retrieve the Models attributes and use them accordingly? Thank you!

Upvotes: 0

Views: 98

Answers (1)

Donkarnash
Donkarnash

Reputation: 12835

Following the conventions the relationship definition in the Image model should be

//-----------------------------Option 1------------------------
public function imageable()
{
    return $this->morphTo();
}

//Access the related like
$image->imageable

//-----------------------------Option 2------------------------

//OR if you want to keep it as image, specify type & id columns
public function image()
{
    return $this->morphTo('image', 'imageable_type', 'imageable_id');
}

//Access the related like
$image->image

Upvotes: 1

Related Questions