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

dmag's avatar
Level 6

method on a Model that returns scoped query results

How can I make a method on a model to return a query results as instead of query Builder instance as in the case of query scopes?

Let's say I have a model that has numerous columns with username and password among them. So currently to get the username and password array from the model I have to do this:

MyModel::credentials($userId)->first(['username', 'password'])->toArray();

I'd like to find out if there's a way in Laravel to return query result from Model's method? So I ideally, I'd want to get the result like this:

MyModel::credentials($userId);
/*
array:2 [
    'username' => 'name',
    'password' => 'pass',
]
*/
class MyModel extends Model
{
    public function scopeCredentials($query, $userId)
    {
        return $query->where('user_id', $userId);
    }
}
0 likes
3 replies
christian-qode's avatar

Hi @dmag you can create a new (public) method/function in the MyModel model to execute the query and returning only the username and password.

1 like
SilenceBringer's avatar
Level 55

@dmag and - what's the problem?

class MyModel extends Model
{
    public function credentials($userId)
    {
        return (new self)->where('user_id', $userId)->first(['username', 'password']);
    }
}
1 like
dmag's avatar
Level 6

@SilenceBringer I though there was some fluent Laravel way to achieve this ))). Thank you for the answer, I'll use it.

Please or to participate in this conversation.