Matrix Blocks

If you’ve ever worked with a hairball of content and markup managed in an increasingly-fragile WYSIWYG field, you’re probably going to like Matrix blocks.

Matrix blocks are groupings of fields an editor can use to build and rearrange content. They can be critical in supporting flexible, customizable content for an editor that’s balanced with the kind of discrete, well-modeled content a developer wants to work with.

# Querying Matrix Blocks

You can fetch Matrix blocks in your templates or PHP code using Matrix block queries.

{# Create a new Matrix block query #}
{% set myMatrixBlockQuery = craft.matrixBlocks() %}

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

See Element Queries to learn about how element queries work.

# Example

We can display content from all the Matrix blocks of an element by doing the following:

  1. Create a Matrix block query with craft.matrixBlocks().
  2. Set the owner, fieldId, and type parameters on it.
  3. Fetch the Matrix blocks with .all().
  4. Loop through the Matrix blocks using a for (opens new window) tag to output the contents.
{# Create a Matrix block query with the 'owner', 'fieldId', and 'type' parameters #}
{% set myMatrixBlockQuery = craft.matrixBlocks()
  .owner(myEntry)
  .fieldId(10)
  .type('text') %}

{# Fetch the Matrix blocks #}
{% set matrixBlocks = myMatrixBlockQuery.all() %}

{# Display their contents #}
{% for block in matrixBlocks %}
  <p>{{ block.text }}</p>
{% endfor %}

In order for the returned Matrix block(s) to be populated with their custom field content, you will need to either set the fieldId or id parameter.

# Parameters

Matrix block queries support the following parameters:

Param Description
addOrderBy Adds additional ORDER BY columns to the query.
afterPopulate Performs any post-population processing on elements.
allowOwnerDrafts Narrows the query results based on whether the Matrix blocks’ owners are drafts.
allowOwnerRevisions Narrows the query results based on whether the Matrix blocks’ owners are revisions.
andRelatedTo Narrows the query results to only Matrix blocks that are related to certain other elements.
anyStatus Removes element filters based on their statuses.
asArray Causes the query to return matching Matrix blocks as arrays of data, rather than MatrixBlock (opens new window) objects.
cache Enables query cache for this Query.
clearCachedResult Clears the cached result (opens new window).
dateCreated Narrows the query results based on the Matrix blocks’ creation dates.
dateUpdated Narrows the query results based on the Matrix blocks’ last-updated dates.
field Narrows the query results based on the field the Matrix blocks belong to.
fieldId Narrows the query results based on the field the Matrix blocks belong to, per the fields’ IDs.
fields Returns the list of fields that should be returned by default by toArray() (opens new window) when no specific fields are specified.
fixedOrder Causes the query results to be returned in the order specified by id.
id Narrows the query results based on the Matrix blocks’ IDs.
ignorePlaceholders Causes the query to return matching Matrix blocks 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.
limit Determines the number of Matrix blocks that should be returned.
offset Determines how many Matrix blocks should be skipped in the results.
orderBy Determines the order that the Matrix blocks should be returned in. (If empty, defaults to sortOrder ASC.)
owner Sets the ownerId and siteId parameters based on a given element.
ownerId Narrows the query results based on the owner element of the Matrix blocks, per the owners’ IDs.
preferSites If unique is set, this determines which site should be selected when querying multi-site elements.
relatedTo Narrows the query results to only Matrix blocks that are related to certain other elements.
search Narrows the query results to only Matrix blocks that match a search query.
site Determines which site(s) the Matrix blocks should be queried in.
siteId Determines which site(s) the Matrix blocks should be queried in, per the site’s ID.
siteSettingsId Narrows the query results based on the Matrix blocks’ IDs in the elements_sites table.
status Narrows the query results based on the Matrix blocks’ statuses.
trashed Narrows the query results to only Matrix blocks that have been soft-deleted.
type Narrows the query results based on the Matrix blocks’ block types.
typeId Narrows the query results based on the Matrix blocks’ block types, per the types’ IDs.
uid Narrows the query results based on the Matrix blocks’ UIDs.
unique Determines whether only elements with unique IDs should be returned by the query.
with Causes the query to return matching Matrix blocks eager-loaded with related elements.

# addOrderBy

Adds additional ORDER BY columns to the query.

# afterPopulate

Performs any post-population processing on elements.

# allowOwnerDrafts

Narrows the query results based on whether the Matrix blocks’ owners are drafts.

Possible values include:

Value Fetches Matrix blocks…
true which can belong to a draft.
false which cannot belong to a draft.

# allowOwnerRevisions

Narrows the query results based on whether the Matrix blocks’ owners are revisions.

Possible values include:

Value Fetches Matrix blocks…
true which can belong to a revision.
false which cannot belong to a revision.

# andRelatedTo

Narrows the query results to only Matrix blocks 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 Matrix blocks that are related to myCategoryA and myCategoryB #}
{% set MatrixBlocks = craft.matrixBlocks()
  .relatedTo(myCategoryA)
  .andRelatedTo(myCategoryB)
  .all() %}

# anyStatus

Removes element filters based on their statuses.

{# Fetch all Matrix blocks, regardless of status #}
{% set MatrixBlocks = craft.matrixBlocks()
  .anyStatus()
  .all() %}

# asArray

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

{# Fetch Matrix blocks as arrays #}
{% set MatrixBlocks = craft.matrixBlocks()
  .asArray()
  .all() %}

# cache

Enables query cache for this Query.

# clearCachedResult

Clears the cached result (opens new window).

# dateCreated

Narrows the query results based on the Matrix blocks’ creation dates.

Possible values include:

Value Fetches Matrix blocks…
'>= 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 Matrix blocks created last month #}
{% set start = date('first day of last month')|atom %}
{% set end = date('first day of this month')|atom %}

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

# dateUpdated

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

Possible values include:

Value Fetches Matrix blocks…
'>= 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 Matrix blocks updated in the last week #}
{% set lastWeek = date('1 week ago')|atom %}

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

# field

Narrows the query results based on the field the Matrix blocks belong to.

Possible values include:

Value Fetches Matrix blocks…
'foo' in a field with a handle of foo.
'not foo' not in a field with a handle of foo.
['foo', 'bar'] in a field with a handle of foo or bar.
['not', 'foo', 'bar'] not in a field with a handle of foo or bar.
a craft\fields\Matrix (opens new window) object in a field represented by the object.
{# Fetch Matrix blocks in the Foo field #}
{% set MatrixBlocks = craft.matrixBlocks()
  .field('foo')
  .all() %}

# fieldId

Narrows the query results based on the field the Matrix blocks belong to, per the fields’ IDs.

Possible values include:

Value Fetches Matrix blocks…
1 in a field with an ID of 1.
'not 1' not in a field with an ID of 1.
[1, 2] in a field with an ID of 1 or 2.
['not', 1, 2] not in a field with an ID of 1 or 2.
{# Fetch Matrix blocks in the field with an ID of 1 #}
{% set MatrixBlocks = craft.matrixBlocks()
  .fieldId(1)
  .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;
    },
];

# 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 Matrix blocks in a specific order #}
{% set MatrixBlocks = craft.matrixBlocks()
  .id([1, 2, 3, 4, 5])
  .fixedOrder()
  .all() %}

# id

Narrows the query results based on the Matrix blocks’ IDs.

Possible values include:

Value Fetches Matrix blocks…
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 Matrix block by its ID #}
{% set MatrixBlock = craft.matrixBlocks()
  .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 Matrix blocks 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 Matrix blocks in reverse #}
{% set MatrixBlocks = craft.matrixBlocks()
  .inReverse()
  .all() %}

# limit

Determines the number of Matrix blocks that should be returned.

{# Fetch up to 10 Matrix blocks  #}
{% set MatrixBlocks = craft.matrixBlocks()
  .limit(10)
  .all() %}

# offset

Determines how many Matrix blocks should be skipped in the results.

{# Fetch all Matrix blocks except for the first 3 #}
{% set MatrixBlocks = craft.matrixBlocks()
  .offset(3)
  .all() %}

# orderBy

Determines the order that the Matrix blocks should be returned in. (If empty, defaults to sortOrder ASC.)

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

# owner

Sets the ownerId and siteId parameters based on a given element.

{# Fetch Matrix blocks created for this entry #}
{% set MatrixBlocks = craft.matrixBlocks()
  .owner(myEntry)
  .all() %}

# ownerId

Narrows the query results based on the owner element of the Matrix blocks, per the owners’ IDs.

Possible values include:

Value Fetches Matrix blocks…
1 created for an element with an ID of 1.
'not 1' not created for an element with an ID of 1.
[1, 2] created for an element with an ID of 1 or 2.
['not', 1, 2] not created for an element with an ID of 1 or 2.
{# Fetch Matrix blocks created for an element with an ID of 1 #}
{% set MatrixBlocks = craft.matrixBlocks()
  .ownerId(1)
  .all() %}

# preferSites

If unique 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 Matrix blocks from Site A, or Site B if they don’t exist in Site A #}
{% set MatrixBlocks = craft.matrixBlocks()
  .site('*')
  .unique()
  .preferSites(['a', 'b'])
  .all() %}

# relatedTo

Narrows the query results to only Matrix blocks 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 Matrix blocks that are related to myCategory #}
{% set MatrixBlocks = craft.matrixBlocks()
  .relatedTo(myCategory)
  .all() %}

Narrows the query results to only Matrix blocks 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 Matrix blocks that match the search query #}
{% set MatrixBlocks = craft.matrixBlocks()
  .search(searchQuery)
  .all() %}

# site

Determines which site(s) the Matrix blocks should be queried in.

The current site will be used by default.

Possible values include:

Value Fetches Matrix blocks…
'foo' from the site with a handle of foo.
['foo', 'bar'] from a site with a handle of foo or bar.
['not', 'foo', 'bar'] not in a site with a handle of foo or bar.
a craft\models\Site (opens new window) object from the site represented by the object.
'*' from any site.

If multiple sites are specified, elements that belong to multiple sites will be returned multiple times. If you only want unique elements to be returned, use unique in conjunction with this.

{# Fetch Matrix blocks from the Foo site #}
{% set MatrixBlocks = craft.matrixBlocks()
  .site('foo')
  .all() %}

# siteId

Determines which site(s) the Matrix blocks should be queried in, per the site’s ID.

The current site will be used by default.

Possible values include:

Value Fetches Matrix blocks…
1 from the site with an ID of 1.
[1, 2] from a site with an ID of 1 or 2.
['not', 1, 2] not in a site with an ID of 1 or 2.
'*' from any site.
{# Fetch Matrix blocks from the site with an ID of 1 #}
{% set MatrixBlocks = craft.matrixBlocks()
  .siteId(1)
  .all() %}

# siteSettingsId

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

Possible values include:

Value Fetches Matrix blocks…
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 Matrix block by its ID in the elements_sites table #}
{% set MatrixBlock = craft.matrixBlocks()
  .siteSettingsId(1)
  .one() %}

# status

Narrows the query results based on the Matrix blocks’ statuses.

Possible values include:

Value Fetches Matrix blocks…
'enabled' (default) that are enabled.
'disabled' that are disabled.
['not', 'disabled'] that are not disabled.
{# Fetch disabled Matrix blocks #}
{% set MatrixBlocks = craft.matrixBlocks()
  .status('disabled')
  .all() %}

# trashed

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

{# Fetch trashed Matrix blocks #}
{% set MatrixBlocks = craft.matrixBlocks()
  .trashed()
  .all() %}

# type

Narrows the query results based on the Matrix blocks’ block types.

Possible values include:

Value Fetches Matrix blocks…
'foo' of a type with a handle of foo.
'not foo' not of a type with a handle of foo.
['foo', 'bar'] of a type with a handle of foo or bar.
['not', 'foo', 'bar'] not of a type with a handle of foo or bar.
an MatrixBlockType (opens new window) object of a type represented by the object.
{# Fetch Matrix blocks with a Foo block type #}
{% set MatrixBlocks = myEntry.myMatrixField
  .type('foo')
  .all() %}

# typeId

Narrows the query results based on the Matrix blocks’ block types, per the types’ IDs.

Possible values include:

Value Fetches Matrix blocks…
1 of a type with an ID of 1.
'not 1' not of a type with an ID of 1.
[1, 2] of a type with an ID of 1 or 2.
['not', 1, 2] not of a type with an ID of 1 or 2.
{# Fetch Matrix blocks of the block type with an ID of 1 #}
{% set MatrixBlocks = myEntry.myMatrixField
  .typeId(1)
  .all() %}

# uid

Narrows the query results based on the Matrix blocks’ UIDs.

{# Fetch the Matrix block by its UID #}
{% set MatrixBlock = craft.matrixBlocks()
  .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx')
  .one() %}

# unique

Determines whether only elements with unique IDs should be returned by the query.

This should be used when querying elements from multiple sites at the same time, if “duplicate” results is not desired.

{# Fetch unique Matrix blocks across all sites #}
{% set MatrixBlocks = craft.matrixBlocks()
  .site('*')
  .unique()
  .all() %}

# with

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

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

{# Fetch Matrix blocks eager-loaded with the "Related" field’s relations #}
{% set MatrixBlocks = craft.matrixBlocks()
  .with(['related'])
  .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!