Users

Users are Craft’s representation of people.

Each user has an email address and username by default, and optional fields for a name, photo, and password. Like other elements, users can have any number of additional custom fields.

There are also preferences for localization, accessibility, and debugging that may be relevant depending on how you build your site and whether you grant the user access to the control panel.

Users can be part of groups you create that fine-tune permissions.

# Querying Users

You can fetch users in your templates or PHP code using user queries.

{# Create a new user query #}
{% set myUserQuery = craft.users() %}

Once you’ve created a user query, you can set parameters on it to narrow down the results, and then execute it by calling .all(). An array of User (opens new window) objects will be returned.

See Element Queries to learn about how element queries work.

# Example

We can display a list of the users in an “Authors” user group by doing the following:

  1. Create a user query with craft.users().
  2. Set the group parameter on it.
  3. Fetch the users with .all().
  4. Loop through the users using a for (opens new window) tag to create the list HTML.
{# Create a user query with the 'group' parameter #}
{% set myUserQuery = craft.users()
  .group('authors') %}

{# Fetch the users #}
{% set users = myUserQuery.all() %}

{# Display the list #}
<ul>
  {% for user in users %}
    <li><a href="{{ url('authors/'~user.username) }}">{{ user.name }}</a></li>
  {% endfor %}
</ul>

# Parameters

User queries support the following parameters:

Param Description
addOrderBy Adds additional ORDER BY columns to the query.
admin Narrows the query results to only users that have admin accounts.
afterPopulate Performs any post-population processing on elements.
andRelatedTo Narrows the query results to only users that are related to certain other elements.
anyStatus Removes element filters based on their statuses.
asArray Causes the query to return matching users as arrays of data, rather than User (opens new window) objects.
cache Enables query cache for this Query.
can Narrows the query results to only users that have a certain user permission, either directly on the user account or through one of their user groups.
clearCachedResult Clears the cached result (opens new window).
dateCreated Narrows the query results based on the users’ creation dates.
dateUpdated Narrows the query results based on the users’ last-updated dates.
email Narrows the query results based on the users’ email addresses.
fields Returns the list of fields that should be returned by default by toArray() (opens new window) when no specific fields are specified.
firstName Narrows the query results based on the users’ first names.
fixedOrder Causes the query results to be returned in the order specified by id.
group Narrows the query results based on the user group the users belong to.
groupId Narrows the query results based on the user group the users belong to, per the groups’ IDs.
hasPhoto Narrows the query results to only users that have (or don’t have) a user photo.
id Narrows the query results based on the users’ IDs.
ignorePlaceholders Causes the query to return matching users as they are stored in the database, ignoring matching placeholder elements that were set by craft\services\Elements::setPlaceholderElement() (opens new window).
inReverse Causes the query results to be returned in reverse order.
lastLoginDate Narrows the query results based on the users’ last login dates.
lastName Narrows the query results based on the users’ last names.
limit Determines the number of users that should be returned.
offset Determines how many users should be skipped in the results.
orderBy Determines the order that the users should be returned in. (If empty, defaults to username ASC.)
preferSites If unique() (opens new window) is set, this determines which site should be selected when querying multi-site elements.
relatedTo Narrows the query results to only users that are related to certain other elements.
search Narrows the query results to only users that match a search query.
siteSettingsId Narrows the query results based on the users’ IDs in the elements_sites table.
status Narrows the query results based on the users’ statuses.
trashed Narrows the query results to only users that have been soft-deleted.
uid Narrows the query results based on the users’ UIDs.
username Narrows the query results based on the users’ usernames.
with Causes the query to return matching users eager-loaded with related elements.
withGroups Causes the query to return matching users eager-loaded with their user groups.

# addOrderBy

Adds additional ORDER BY columns to the query.

# admin

Narrows the query results to only users that have admin accounts.

{# Fetch admins #}
{% set users = craft.users()
  .admin()
  .all() %}

# afterPopulate

Performs any post-population processing on elements.

# andRelatedTo

Narrows the query results to only users that are related to certain other elements.

See Relations (opens new window) for a full explanation of how to work with this parameter.

{# Fetch all users that are related to myCategoryA and myCategoryB #}
{% set users = craft.users()
  .relatedTo(myCategoryA)
  .andRelatedTo(myCategoryB)
  .all() %}

# anyStatus

Removes element filters based on their statuses.

{# Fetch all users, regardless of status #}
{% set users = craft.users()
  .anyStatus()
  .all() %}

# asArray

Causes the query to return matching users as arrays of data, rather than User (opens new window) objects.

{# Fetch users as arrays #}
{% set users = craft.users()
  .asArray()
  .all() %}

# cache

Enables query cache for this Query.

# can

Narrows the query results to only users that have a certain user permission, either directly on the user account or through one of their user groups.

See User Management (opens new window) for a full list of available user permissions defined by Craft.

{# Fetch users that can access the control panel #}
{% set users = craft.users()
  .can('accessCp')
  .all() %}

# clearCachedResult

Clears the cached result (opens new window).

# dateCreated

Narrows the query results based on the users’ creation dates.

Possible values include:

Value Fetches users…
'>= 2018-04-01' that were created on or after 2018-04-01.
'< 2018-05-01' that were created before 2018-05-01
['and', '>= 2018-04-04', '< 2018-05-01'] that were created between 2018-04-01 and 2018-05-01.
{# Fetch users created last month #}
{% set start = date('first day of last month')|atom %}
{% set end = date('first day of this month')|atom %}

{% set users = craft.users()
  .dateCreated(['and', ">= #{start}", "< #{end}"])
  .all() %}

# dateUpdated

Narrows the query results based on the users’ last-updated dates.

Possible values include:

Value Fetches users…
'>= 2018-04-01' that were updated on or after 2018-04-01.
'< 2018-05-01' that were updated before 2018-05-01
['and', '>= 2018-04-04', '< 2018-05-01'] that were updated between 2018-04-01 and 2018-05-01.
{# Fetch users updated in the last week #}
{% set lastWeek = date('1 week ago')|atom %}

{% set users = craft.users()
  .dateUpdated(">= #{lastWeek}")
  .all() %}

# email

Narrows the query results based on the users’ email addresses.

Possible values include:

Value Fetches users…
'me@domain.tld' with an email of me@domain.tld.
'not me@domain.tld' not with an email of me@domain.tld.
'*@domain.tld' with an email that ends with @domain.tld.
{# Fetch users with a .co.uk domain on their email address #}
{% set users = craft.users()
  .email('*.co.uk')
  .all() %}

# fields

Returns the list of fields that should be returned by default by toArray() (opens new window) when no specific fields are specified.

A field is a named element in the returned array by toArray() (opens new window). This method should return an array of field names or field definitions. If the former, the field name will be treated as an object property name whose value will be used as the field value. If the latter, the array key should be the field name while the array value should be the corresponding field definition which can be either an object property name or a PHP callable returning the corresponding field value. The signature of the callable should be:

function ($model, $field) {
    // return field value
}

For example, the following code declares four fields:

  • email: the field name is the same as the property name email;
  • firstName and lastName: the field names are firstName and lastName, and their values are obtained from the first_name and last_name properties;
  • fullName: the field name is fullName. Its value is obtained by concatenating first_name and last_name.
return [
    'email',
    'firstName' => 'first_name',
    'lastName' => 'last_name',
    'fullName' => function ($model) {
        return $model->first_name . ' ' . $model->last_name;
    },
];

# firstName

Narrows the query results based on the users’ first names.

Possible values include:

Value Fetches users…
'Jane' with a first name of Jane.
'not Jane' not with a first name of Jane.
{# Fetch all the Jane's #}
{% set users = craft.users()
  .firstName('Jane')
  .all() %}

# fixedOrder

Causes the query results to be returned in the order specified by id.

If no IDs were passed to id, setting this to true will result in an empty result set.

{# Fetch users in a specific order #}
{% set users = craft.users()
  .id([1, 2, 3, 4, 5])
  .fixedOrder()
  .all() %}

# group

Narrows the query results based on the user group the users belong to.

Possible values include:

Value Fetches users…
'foo' in a group with a handle of foo.
'not foo' not in a group with a handle of foo.
['foo', 'bar'] in a group with a handle of foo or bar.
['and', 'foo', 'bar'] in both groups with handles of foo or bar.
['not', 'foo', 'bar'] not in a group with a handle of foo or bar.
a UserGroup (opens new window) object in a group represented by the object.
{# Fetch users in the Foo user group #}
{% set users = craft.users()
  .group('foo')
  .all() %}

# groupId

Narrows the query results based on the user group the users belong to, per the groups’ IDs.

Possible values include:

Value Fetches users…
1 in a group with an ID of 1.
'not 1' not in a group with an ID of 1.
[1, 2] in a group with an ID of 1 or 2.
['and', 1, 2] in both groups with IDs of 1 or 2.
['not', 1, 2] not in a group with an ID of 1 or 2.
{# Fetch users in a group with an ID of 1 #}
{% set users = craft.users()
  .groupId(1)
  .all() %}

# hasPhoto

Narrows the query results to only users that have (or don’t have) a user photo.

{# Fetch users with photos #}
{% set users = craft.users()
  .hasPhoto()
  .all() %}

# id

Narrows the query results based on the users’ IDs.

Possible values include:

Value Fetches users…
1 with an ID of 1.
'not 1' not with an ID of 1.
[1, 2] with an ID of 1 or 2.
['not', 1, 2] not with an ID of 1 or 2.
{# Fetch the user by its ID #}
{% set user = craft.users()
  .id(1)
  .one() %}

This can be combined with fixedOrder if you want the results to be returned in a specific order.

# ignorePlaceholders

Causes the query to return matching users as they are stored in the database, ignoring matching placeholder elements that were set by craft\services\Elements::setPlaceholderElement() (opens new window).

# inReverse

Causes the query results to be returned in reverse order.

{# Fetch users in reverse #}
{% set users = craft.users()
  .inReverse()
  .all() %}

# lastLoginDate

Narrows the query results based on the users’ last login dates.

Possible values include:

Value Fetches users…
'>= 2018-04-01' that last logged-in on or after 2018-04-01.
'< 2018-05-01' that last logged-in before 2018-05-01
['and', '>= 2018-04-04', '< 2018-05-01'] that last logged-in between 2018-04-01 and 2018-05-01.
{# Fetch users that logged in recently #}
{% set aWeekAgo = date('7 days ago')|atom %}

{% set users = craft.users()
  .lastLoginDate(">= #{aWeekAgo}")
  .all() %}

# lastName

Narrows the query results based on the users’ last names.

Possible values include:

Value Fetches users…
'Doe' with a last name of Doe.
'not Doe' not with a last name of Doe.
{# Fetch all the Doe's #}
{% set users = craft.users()
  .lastName('Doe')
  .all() %}

# limit

Determines the number of users that should be returned.

{# Fetch up to 10 users  #}
{% set users = craft.users()
  .limit(10)
  .all() %}

# offset

Determines how many users should be skipped in the results.

{# Fetch all users except for the first 3 #}
{% set users = craft.users()
  .offset(3)
  .all() %}

# orderBy

Determines the order that the users should be returned in. (If empty, defaults to username ASC.)

{# Fetch all users in order of date created #}
{% set users = craft.users()
  .orderBy('dateCreated ASC')
  .all() %}

# preferSites

If unique() (opens new window) is set, this determines which site should be selected when querying multi-site elements.

For example, if element “Foo” exists in Site A and Site B, and element “Bar” exists in Site B and Site C, and this is set to ['c', 'b', 'a'], then Foo will be returned for Site B, and Bar will be returned for Site C.

If this isn’t set, then preference goes to the current site.

{# Fetch unique users from Site A, or Site B if they don’t exist in Site A #}
{% set users = craft.users()
  .site('*')
  .unique()
  .preferSites(['a', 'b'])
  .all() %}

# relatedTo

Narrows the query results to only users that are related to certain other elements.

See Relations (opens new window) for a full explanation of how to work with this parameter.

{# Fetch all users that are related to myCategory #}
{% set users = craft.users()
  .relatedTo(myCategory)
  .all() %}

Narrows the query results to only users that match a search query.

See Searching (opens new window) for a full explanation of how to work with this parameter.

{# Get the search query from the 'q' query string param #}
{% set searchQuery = craft.app.request.getQueryParam('q') %}

{# Fetch all users that match the search query #}
{% set users = craft.users()
  .search(searchQuery)
  .all() %}

# siteSettingsId

Narrows the query results based on the users’ IDs in the elements_sites table.

Possible values include:

Value Fetches users…
1 with an elements_sites ID of 1.
'not 1' not with an elements_sites ID of 1.
[1, 2] with an elements_sites ID of 1 or 2.
['not', 1, 2] not with an elements_sites ID of 1 or 2.
{# Fetch the user by its ID in the elements_sites table #}
{% set user = craft.users()
  .siteSettingsId(1)
  .one() %}

# status

Narrows the query results based on the users’ statuses.

Possible values include:

Value Fetches users…
'active' (default) with active accounts.
'suspended' with suspended accounts.
'pending' with accounts that are still pending activation.
'locked' with locked accounts (regardless of whether they’re active or suspended).
['active', 'suspended'] with active or suspended accounts.
['not', 'active', 'suspended'] without active or suspended accounts.
{# Fetch active and locked users #}
{% set users = craft.users()
  .status(['active', 'locked'])
  .all() %}

# trashed

Narrows the query results to only users that have been soft-deleted.

{# Fetch trashed users #}
{% set users = craft.users()
  .trashed()
  .all() %}

# uid

Narrows the query results based on the users’ UIDs.

{# Fetch the user by its UID #}
{% set user = craft.users()
  .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx')
  .one() %}

# username

Narrows the query results based on the users’ usernames.

Possible values include:

Value Fetches users…
'foo' with a username of foo.
'not foo' not with a username of foo.
{# Get the requested username #}
{% set requestedUsername = craft.app.request.getSegment(2) %}

{# Fetch that user #}
{% set user = craft.users()
  .username(requestedUsername|literal)
  .one() %}

# with

Causes the query to return matching users eager-loaded with related elements.

See Eager-Loading Elements (opens new window) for a full explanation of how to work with this parameter.

{# Fetch users eager-loaded with the "Related" field’s relations #}
{% set users = craft.users()
  .with(['related'])
  .all() %}

# withGroups

Causes the query to return matching users eager-loaded with their user groups.

Possible values include:

Value Fetches users…
'>= 2018-04-01' that last logged-in on or after 2018-04-01.
'< 2018-05-01' that last logged-in before 2018-05-01
['and', '>= 2018-04-04', '< 2018-05-01'] that last logged-in between 2018-04-01 and 2018-05-01.
{# fetch users with their user groups #}
{% set users = craft.users()
  .withGroups()
  .all() %}
Parts of this page are generated or assembled by automations. While we greatly appreciate contributions to the documentation, reporting automated content issues will allow us to fix them at the source!