ignaciodev's avatar

How to test Elloquent local scope coming from trait?

Hello! How can I test local scopes that are coming from a trait?

This is the trait:

trait HasHashedID
{
    public static function dehashID(string $hashedID):string
    {
        return Hashids::decode($hashedID)[0];
    }

    public function scopeFindByHashedID(Builder $query, string $hashedID):self
    {
        return $query->find(self::dehashID(hashedID: $hashedID));
    }

    public function scopeFindByHashedIDOrFail(Builder $query, string $hashedID):self
    {
        return $query->findOrFail(self::dehashID(hashedID: $hashedID));
    }
}

I managed to write a test for the dehashID() method. However, I'd like to know how to test the other two methods? The local-scope ones.

Thank you!!

0 likes
6 replies
tykus's avatar
tykus
Best Answer
Level 104

These scopes are not valid - a scope mutates the Builder instance; it does not return a query result.

2 likes
ignaciodev's avatar

(these scope methods do work though, i tried them on Tinker and got the desired results...)

martinbean's avatar

@ignaciodev They’re still not scopes, though. Scopes manipulate a query by adding where clauses, order clauses, etc. They’re not for executing a query and returning the results.

What you have should just methods (as @tykus says), not scopes.

Please or to participate in this conversation.