Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

kenny11's avatar

Raw query

I have a polymorphic relation.

Class Reply

public function replyable()
{
    return $this->morphTo();
}

Which belongs to User and Trainer.

When I fetch replies I want an authenticated user's reply placed first.

So, if an auth user is a trainer, trainer's reply should be first and an auth user is a normal user, user's reply should be first.

This is what I got for now.

public function index(Question $question)
{
        if (!! trainer()) {
            //if an auth user is a trainer, place their posts first in the response data
            return $question->replies()->orderByRaw("FIELD(replyable_id, ".trainer()->id.") DESC")->inRandomOrder()->with('replyable', 'question')->paginate(15);
        }

        if (auth()->check()) {
            //if an auth user is a normal user, place their posts first in the response data
            return $question->replies()->orderByRaw("FIELD(replyable_id, ".auth()->id().") DESC")->inRandomOrder()->with('replyable', 'question')->paginate(15);
        }

        return $question->replies()->with('replyable', 'question')->inRandomOrder()->paginate(15);
}

I need to restraint a query based on replyable_type. So, an auth user is a trainer, replies should be ordered first with a reply which has replyable_type of trainer with replyable_id of whatever the authenticated user (trainer) id is.

This query is not working.

 if (!! trainer()) {
            //if an auth user is a trainer, place their posts first in the response data
            return $question->replies()->orderByRaw("where replyable_type = trainers FIELD(replyable_id, ".trainer()->id.") DESC")->inRandomOrder()->with('replyable', 'question')->paginate(15);
        }
0 likes
0 replies

Please or to participate in this conversation.