Mr.Singh
Mr.Singh

Reputation: 1781

Laravel Polymorphic Relationships with order by

Laravel version 7.2.5.

I am using Polymorphic Relationships to store the access logs (login, logout) for multi-role application.

The data storing part is working completely fine. Now, I need to show the list of records in desc format with pagination. But, It's loading the data in the asc format

SomeModel.php

class SomeModel extends Model
{
    /**
     * Polymorphic Relationships
     */
    public function loginLog()
    {
        return $this->morphMany(LoginLog::class, 'employable');
    }

    public function show($token)
    {
        return self::where([
            'token' => $token,
        ])->with([
            'loginLog:employable_id,ip,created_at,updated_at'
        ])->first() ?? null;
    }
}

I did find the solution. But, somehow it doesn't feel the appropriate way to solve this issue.

Here is the link Laravel order results by column on polymorphic table

Upvotes: 0

Views: 1205

Answers (2)

Mr.Singh
Mr.Singh

Reputation: 1781

I found another way to solve this issue...

class SomeModel extends Model
{
    /**
     * Polymorphic Relationships
     */
    public function loginLog()
    {
        return $this->morphMany(LoginLog::class, 'employable');
    }

    public function show($token, $pagination = 0)
    {
        return self::where([
            'token' => $token,
        ])->with([
            'loginLog' => function ($query) use ($pagination) {
                return $query->select([
                    'employable_id',
                    'ip',
                    'created_at',
                    'updated_at',
                ])
                ->skip($pagination)
                ->take(\Common::paginationLimit())
                ->orderBy('id', 'DESC');
            }
        ])
        ->orderBy('id', 'DESC')
        ->first('id') ?? null;
    }
}

Since I do not need the base table's parameters, therefore, I am fetching only id from it.

Also, with this way I am able to use the pagination too (I am using loadmore pagination).

Upvotes: 0

Kamlesh Paul
Kamlesh Paul

Reputation: 12391

Try this

class SomeModel extends Model
{
    /**
     * Polymorphic Relationships
     */
    public function loginLog()
    {
        return $this
            ->morphMany(LoginLog::class, 'employable')
            ->latest();
    }
}

Upvotes: 1

Related Questions