Answer the question
In order to leave comments, you need to log in
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) {
Здесь имя изображения преобразуется в адрес
}
Answer the question
In order to leave comments, you need to log in
For example, the model of your pictures:
class Image extends Model
{
public function imageable()
{
return $this->morphTo();
}
}
class Post extends Model
{
public function images()
{
return $this->morphMany('App\Image', 'imageable');
}
}
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 questionAsk a Question
731 491 924 answers to any question