mercredi 4 novembre 2015

Retrieve parent class within morph relationship

I have this code

//ImageableTrait
trait ImageableTrait
{
    public function images()
    {
        return $this->morphMany(Image::class, 'imageable')
            ->orderBy('order', 'ASC');
    }
}

//User
class User extend Model
{
    use ImageableTrait;
}

//Post
class Post extend Model
{
    use ImageableTrait;
}

class ImageCollection extends Collection
{
    public function firstOrDefault()
    {
        if ($this->count() === 0) {
            $image = new Image();
            $image->id = 'default';
            $image->imageable_type = '/* I need the parent className here */';
            $image->imageable_id = '.';
        }

        return $this->first();
    }
}

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

    public function newCollection(array $models = [])
    {
        return new ImageCollection($models);
    }

    public function path($size)
    {
        //Here, there is some logic to build the image path and it needs
        //the imageable_type attribute no matter if there is
        //an image record in the database or not
        return;
    }
}

I want to be able to do so

$path = User::find($id)->images->firstOrDefault()->path('large');

But I can't figure out how to get the parent class name to build the path properly...

I tried with $morphClass or getMorphClass() but can't figure out how to use it properly or if it is even the right way to do it.

Any thoughts on that?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire