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

fbc's avatar
Level 2

Trying to use sortBy() or sortByDesc() gives error and last() as well.

This:

            $lastbill = Bill::where('project_id', $project->id)->where('bill_type', 'p')->sortByDesc('created_at')->first();

produces error:

Call to undefined method Illuminate\Database\Eloquent\Builder::sortByDesc()

This:

$lastbill = Bill::where('project_id', $project->id)->where('bill_type', 'p')->last();

produces error:

Call to undefined method Illuminate\Database\Eloquent\Builder::last()

I know the record is there because when I do:

dd(Bill::where('project_id', $project->id)->where('bill_type', 'p')->count());

I get:

1
0 likes
2 replies
Nakov's avatar

You are trying to use Collection methods on a Eloquent Builder instance.

so this:

 $lastbill = Bill::where('project_id', $project->id)->where('bill_type', 'p')
    ->get() // this should give you collection
    ->sortByDesc('created_at')->first();

same here:

$lastbill = Bill::where('project_id', $project->id)->where('bill_type', 'p')->get()->last();
1 like

Please or to participate in this conversation.