Search code examples
laravellaravel-medialibrarypolymorphic-relationship

Laravel polymorphic relationship retrieve last record


I am currently using the Spatie media library and I have created my own custom class as follows:

use Spatie\MediaLibrary\Models\Media as BaseMedia;

class TrybzMedia extends BaseMedia
{
    protected $table = 'media';
    protected $appends = ['url'];

    public function getUrlAttribute()
    {
        return $this->getUrl();
    }
}

I have a User class where I have defined a polymorphic relationship:

public function avatar()
{
    return $this->morphMany(TrybzMedia::class, 'model')->where('collection_name', '=', 'avatar');
}

There could be multiple images uploaded so what I am trying to achieve is get the last record for the relationship. I have attempted the following with no luck:

public function avatar()
{
    return $this->morphMany(TrybzMedia::class, 'model')->where('collection_name', '=', 'avatar')->last();
}

I want to contain all the code within the definition of the relationship. Is that possible?


Solution

  • You can try using ->limit(1) like :

    public function avatar()
    {
       return $this->morphMany(TrybzMedia::class, 'model')->where('collection_name', '=', 'avatar')->orderBy('put_column_name_here', 'DESC')->limit(1);
    }
    

    You can get last record.:)