Northify
Northify

Reputation: 391

Laravel - Property does not exist on this collection instance

On my Users model I have a query that gives me "Property [manager_id] does not exist on this collection instance" error. I suppose this is because the collection of expiringUsers does not have a single property manager_id, but I'm not sure how to loop through expiringUsers in the query.

What I'm trying to return is a collection of managers where their ID matches the expiring manager_id.

public function scopeManagers()
    {   

        $expiringUsers = $this->ExpiringContractors(); // This returns a collection of users
        return $mangers = $this->where(function($query) use ($expiringUsers){
                    $query->where('id', $expiringUsers->manager_id);
                })->get();



    }

Upvotes: 1

Views: 1147

Answers (1)

Tim Lewis
Tim Lewis

Reputation: 29278

You already said it yourself... If $expiringUsers is a Collection, you can't access manager_id without looping, but you actually don't have to in this case. If you want to query id for those that match any manager_id, you can do that via a whereIn() clause, combined with the pluck() method:

$query->whereIn('id', $expiringUsers->pluck('manager_id'));

And, your code can be simplified to:

public function scopeManagers(){ 
  return $this->where(function($query){
    $query->whereIn('id', $this->ExpiringContractors()->pluck('manager_id'));
  })->get();
}

Note: ExpiringContractors should really be expiringContractors; function names are generally camelCase.

Upvotes: 2

Related Questions