P
P
photosho2016-01-26 03:00:56
Laravel
photosho, 2016-01-26 03:00:56

How to find out the type of an object in a polymorphic relationship?

Hello. There is an "images" table with images associated with a polymorphic relationship (morphTo) with several types of materials. Images for each type are stored on the server in different folders, and the table with images contains not full paths, but only image names. The path to the file is built in the following function:

public function getNameAttribute($name) {
    Здесь имя изображения преобразуется в адрес
}

Is it possible somehow inside this function to determine the type of material to which the image is assigned to generate the path corresponding to it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrzej Wielski, 2016-01-26
@photosho

For example, the model of your pictures:

class Image extends Model
{
    public function imageable()
    {
        return $this->morphTo();
    }
}

And a post with pictures:
class Post extends Model
{
    public function images()
    {
        return $this->morphMany('App\Image', 'imageable');
    }
}

In this case, in the link table, the type of the referenced object (say, App\Post) will be in the imageable_type cell.
I can't check at the moment, but it's logical to assume that such a bunch is what you need:
class Post extends Model
{
    public function images()
    {
        return $this->morphMany('App\Image', 'imageable')->withPivot('imageable_type');
    }
}

public function getNameAttribute() {
    switch($this->pivot->imageable_type){
        case 'App\Post':
            // что вы хотите сделать с $this->name если тип - App\Post
        break;
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question