@ismaile I added that to the model and got this:
$user->library()->beingProcessed();
BadMethodCallException with message 'Call to undefined method Illuminate/Database/Eloquent/Relations/BelongsToMany::beingProcessed()'
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I had a look at Eloquent query scopes, but could not find a way to do the following:
User model:
class User extends Model {
/**
* Returns the items in the user's library.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
function library() {
return $this->belongsToMany(Item::class, UserItem::class, 'user_id', 'item_id')
->withPivot('status');
}
}
Desired behavior:
// Return the items in the library as normal
$user->library()
// Returns the same as:
// $user->library()->wherePivot('status', 'being_processed');
$user->library()->beingProcessed()
// This should attach an item, the same way as:
// $user->library()->attach(1, ['status' => 'being_processed']);
$user->library()->beingProcessed()->attach(1)
Can this be achieved using Eloquent query scopes, or maybe some other way?
I don't think this is possible. attach expects the id and the pivot table values.
You can embed your logic in a method instead:
public function addALibraryBeingProcessed($library_id)
{
$this->library()->attach($library_id, ['status' => 'being_processed']);
}
PS: On a side note, regarding the naming, I would change library to libraries for the methods library and libraryBeingProcessed since we are expecting many libraries per user.
Please or to participate in this conversation.