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.
Oct 25, 2022
3
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);
}
}
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
Please or to participate in this conversation.