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

clinta's avatar

Using latest()->first() in a local query scope on relation gives an error

I have a Task model which has a M:M relationship setup called transfers. This links Task & User models through a pivot table called transfer_task. The following code works fine and displays just the tasks that have been transferred to the current user

$current_user_id = \Auth::user()->id;
$query->orWhereHas('transfers', function ($query) use($current_user_id) {
    $query->where('users.id', $current_user_id);
});

I am trying to grab just the latest entry from the pivot table so I only have the person it was transferred to last in my collection. I need the full transfer history (for elsewhere in the application) which is the reason I have M:M rather than 1:M.

I have tried the following but I get an error message Unknown column tasks.id in where clause

$current_user_id = \Auth::user()->id;
$query->orWhereHas('transfers', function ($query) use($current_user_id) {
    $query->latest()->first();
    $query->where('users.id', $current_user_id);
});

I have basically stuck $query->latest()->first(); before $query->where('users.id', $current_user_id); in an attempt to remove the earlier transfers.

Does anyone know how I can resolve this?

0 likes
5 replies
Snapey's avatar

Please format your code by putting 3 backticks ``` on a line before and after each code block

can't see where you might be asking for anything to do with tasks.id ?

How is $query set? Is this code inside a scope? What model is being scoped?

Snapey's avatar

You should know that addingfirst() executes the query (same as get())

So having it in a scope is not going to work. You could call first() outside of the scope, on the collection, or you could add take(1) to the scope, but bear in mind you are going to get a collection of 1 record so you still need to use first() on the collection to get a single model.

1 like
clinta's avatar

Apologies I am new here. I'll update the question to make it more readable.

It is inside a scope on the Task model

clinta's avatar

I need all the Tasks, just the latest transfer (relation). Won't your answer give me just 1 Task?

Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

An easy fix would be to add a secondary relationship called transfer() which is a belongsTo relationship :)

1 like

Please or to participate in this conversation.