Danny Younes
Danny Younes

Reputation: 619

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?

Upvotes: 0

Views: 1881

Answers (5)

Jordi Touza Bonnin
Jordi Touza Bonnin

Reputation: 1

latestOfMany not works on morphMany.

public function avatar(): HasOne {
    return $this->hasOne(TrybzMedia::class, 'target_id', 'id')
            ->where('target_type', self::class)
            ->latestOfMany();
}

Upvotes: 0

Squarou
Squarou

Reputation: 11

I guess this could do the job ?

public function cover()
{
    $this->morphOne(TrybzMedia::class, 'model')->latestOfMany();
}

See the docs : One Of Many (Polymorphic)

Upvotes: 1

Ravikant Patel
Ravikant Patel

Reputation: 181

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.:)

Upvotes: 2

Danny Younes
Danny Younes

Reputation: 619

The following works:

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

Upvotes: 2

S N Sharma
S N Sharma

Reputation: 1526

You can try with order by and first to get the last or first record.

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

Upvotes: 0

Related Questions