Fields
Nova ships with a variety of fields out of the box, including fields for text inputs, booleans, dates, file uploads, Markdown, and more.
Defining Fields
Each Nova resource contains a fields
method. This method returns an array of fields, which generally extend the Laravel\Nova\Fields\Field
class. Nova ships with a variety of fields out of the box, including fields for text inputs, booleans, dates, file uploads, Markdown, and more.
To add a field to a resource, you may simply add it to the resource’s fields
method. Typically, fields may be created using their static make
method. This method accepts several arguments; however, you usually only need to pass the “human readable” name of the field. Nova will automatically “snake case” this string to determine the underlying database column:
Field Column Conventions
As noted above, Nova will “snake case” the displayable name of the field to determine the underlying database column. However, if necessary, you may pass the column name as the second argument to the field’s make
method:
If the field has a JSON, ArrayObject
, or array cast assigned to it, you may use the ->
operator to specify nested properties within the field:
Showing / Hiding Fields
Often, you will only want to display a field in certain situations. For example, there is typically no need to show a Password
field on a resource index listing. Likewise, you may wish to only display a Created At
field on the creation / update forms. Nova makes it a breeze to hide / show fields on certain pages.
The following methods may be used to show / hide fields based on the display context:
showOnIndex
showOnDetail
showOnCreating
showOnUpdating
showOnPreview
showWhenPeeking
hideFromIndex
hideFromDetail
hideWhenCreating
hideWhenUpdating
onlyOnIndex
onlyOnDetail
onlyOnForms
exceptOnForms
You may chain any of these methods onto your field’s definition in order to instruct Nova where the field should be displayed:
Alternatively, you may pass a callback to the following methods.
showOnIndex
showOnDetail
showOnCreating
showOnUpdating
showWhenPeeking
hideFromIndex
hideFromDetail
hideWhenCreating
hideWhenUpdating
showOnPreview
onlyOnPreview
For show*
methods, the field will be displayed if the given callback returns true
:
For hide*
methods, the field will be hidden if the given callback returns true
:
Showing Fields When Peeking
You may allow a field to be visible when peeking at the resource by invoking the showWhenPeeking
method when defining the field:
Resource Preview Modal
You may also define which fields should be included in the resource’s “preview” modal. This modal can be displayed for a given resource by the user when viewing the resource’s index:
Alternatively, you may pass a callback to the showOnPreview
method:
Dynamic Field Methods
If your application requires it, you may specify a separate list of fields for specific display contexts. For example, imagine you have a resource with the following list of fields:
On your detail page, you may wish to show a combined name via a computed field, followed by the job title. In order to do this, you could add a fieldsForDetail
method to the resource class which returns a separate list of fields that should only be displayed on the resource’s detail page:
The available methods that may be defined for individual display contexts are:
fieldsForIndex
fieldsForDetail
fieldsForInlineCreate
fieldsForCreate
fieldsForUpdate
fieldsForPreview
The fieldsForIndex
, fieldsForDetail
, fieldsForInlineCreate
, fieldsForCreate
,fieldsForUpdate
, and fieldsForPreview
methods always take precedence over the fields
method.
Default Values
There are times you may wish to provide a default value to your fields. Nova offers this functionality via the default
method, which accepts a value or callback. This value will be used as the field’s default input value on the resource’s creation view:
Field Placeholder Text
By default, the placeholder text of a field will be it’s name. You can override the placeholder text of a field that supports placeholders by using the placeholder
method:
Field Hydration
On every create or update request that Nova receives for a given resource, each field’s corresponding model attribute will automatically be filled before the model is persisted to the database. If necessary, you may customize the hydration behavior of a given field using the fillUsing
method:
Field Panels
If your resource contains many fields, your resource “detail” page can become crowded. For that reason, you may choose to break up groups of fields into their own “panels”:
You may accomplish this by creating a new Panel
instance within the fields
method of a resource. Each panel requires a name and an array of fields that belong to that panel:
You may limit the amount of fields shown in a panel by using the limit
method:
Panels with a defined field limit will display a Show All Fields button in order to allow the user to view all of the defined fields when needed.
Sortable Fields
When attaching a field to a resource, you may use the sortable
method to indicate that the resource index may be sorted by the given field:
Field Types
This portion of the documentation only discusses non-relationship fields. To learn more about relationship fields, check out their documentation.
Nova ships with a variety of field types. So, let’s explore all of the available types and their options:
- Audio
- Avatar
- Badge
- Boolean
- Boolean Group
- Code
- Color
- Country
- Currency
- Date
- DateTime
- File
- Gravatar
- Heading
- Hidden
- ID
- Image
- KeyValue
- Markdown
- MultiSelect
- Number
- Password
- Password Confirmation
- Select
- Slug
- Sparkline
- Status
- Stack
- Tag
- Text
- Textarea
- Timezone
- Trix
- UI-Avatar
- URL
- Vapor File
- Vapor Image
Audio Field
The Audio
field extends the File field and accepts the same options and configurations. The Audio
field, unlike the File
field, will display a thumbnail preview of the underlying image when viewing the resource:
By default, the Audio
field allows the user to download the linked file. To disable downloads, you may use the disableDownload
method on the field definition:
You can set the preload attribute of the field by using the preload
method:
To learn more about defining file fields and handling uploads, check out the comprehensive file field documentation.
Avatar Field
The Avatar
field extends the Image field and accepts the same options and configuration:
If a resource contains an Avatar
field, that field will be displayed next to the resource’s title when the resource is displayed in search results:
You may use the squared
method to display the image’s thumbnail with squared edges. Additionally, you may use the rounded
method to display its thumbnails with fully-rounded edges:
Badge Field
The Badge
field can be used to display the status of a Resource
in the index and detail views:
By default, the Badge
field supports four variations: info
, success
, danger
, and warning
. You may define your possible field values and their associated badge types using the map
method:
Alternatively, you may use the types
method to completely replace the built-in badge types and their associated CSS classes. The CSS classes may be provided as a string or an array:
If you only wish to supplement the built-in badge types instead of overwriting all of them, you may use the addTypes
method:
By default the Badge
field is not shown on a resource’s edit or update pages. If you wish to modify the underlying value represented by the Badge
field on your edit forms, define another field in combination with the onlyOnForms
field option.
If you’d like to display your badge with an associated icon, you can use the withIcons
method to direct Nova to display an icon:
If you’d like to customize the icons used when display Badge
fields you can use the icons
method:
If you’d like to customize the label that is displayed you can use the label
method:
You may provide a list of labels using the labels
method:
Boolean Field
The Boolean
field may be used to represent a boolean / “tiny integer” column in your database. For example, assuming your database has a boolean column named active
, you may attach a Boolean
field to your resource like so:
Customizing True / False Values
If you are using values other than true
, false
, 1
, or 0
to represent “true” and “false”, you may instruct Nova to use the custom values recognized by your application. To accomplish this, chain the trueValue
and falseValue
methods onto your field’s definition:
Boolean Group Field
The BooleanGroup
field may be used to group a set of Boolean checkboxes, which are then stored as JSON key-values in the database column they represent. You may create a BooleanGroup
field by providing a set of keys and labels for each option:
The user will be presented with a grouped set of checkboxes which, when saved, will be converted to JSON format:
Before using this field type, you should ensure that the underlying Eloquent attribute is configured to cast to an array
(or equivalent) within your Eloquent model class:
Sometimes, you may wish to exclude values that are true
or false
from display to avoid cluttering the representation of the field. You may accomplish this by invoking the hideFalseValues
or hideTrueValues
methods on the field definition:
If the underlying field is empty, Nova will display “No Data”. You may customize this text using the noValueText
method:
Code Field
The Code
fields provides a beautiful code editor within your Nova administration panel. Generally, code fields should be attached to TEXT
database columns:
You may also attach Code
fields to JSON
database columns. By default, the field will display the value as a JSON string. You may cast the underlying Eloquent attribute to array
, collection
, object
, or json
based on your application’s needs:
By default, Nova will never display a Code
field on a resource index listing.
Editing JSON
If you intend to use a given Code
field instance to only edit JSON, you may chain the json
method onto your field definition:
Nova does not automatically apply the json
validation rule to Code
fields. This rule must be manually specified during validation if you wish for it to be applied.
Syntax Highlighting
You may customize the language syntax highlighting of the Code
field using the language
method:
The Code
field’s currently supported languages are:
dockerfile
htmlmixed
javascript
markdown
nginx
php
ruby
sass
shell
sql
twig
vim
vue
xml
yaml-frontmatter
yaml
Color Field
The Color
field generates a color picker using the HTML5 color
input element:
Country Field
The Country
field generates a Select
field containing a list of the world’s countries. The field will store the country’s corresponding two-letter code:
Currency Field
The Currency
field generates a Number
field that is automatically formatted using the brick/money
PHP package. Nova will use USD
as the default currency; however, this can be changed by modifying the nova.currency
configuration value:
You may override the currency on a per-field basis using the currency
method:
The ext-intl
PHP extension is required to display formatted currency. Or, you may install the symfony/polyfill-intl-icu
Composer package which offers support for the “en” locale.
You may use the min
, max
, and step
methods to set their corresponding attributes on the generated input
control:
If you plan to customize the currency “step” amount using the step
method, you should ensure you always call the step
method after the currency
, asMinorUnits
, and asMajorUnits
methods. Calling these methods after the step
method will override the step
method’s behavior.
The field’s locale will respect the value in your application’s app.locale
configuration value. You can override this behavior by providing a locale code to the locale
method:
Date Field
The Date
field may be used to store a date value (without time). For more information about dates and timezones within Nova, check out the additional date / timezone documentation:
DateTime Field
The DateTime
field may be used to store a date-time value. For more information about dates and timezones within Nova, check out the additional date / timezone documentation:
Email Field
The Email
field may be used to display a column with a mailto:
link on the index and detail views:
File Field
To learn more about defining file fields and handling uploads, please refer to the comprehensive file field documentation.
Gravatar Field
The Gravatar
field does not correspond to any column in your application’s database. Instead, it will display the “Gravatar” image of the model it is associated with.
By default, the Gravatar URL will be generated based on the value of the model’s email
column. However, if your user’s email addresses are not stored in the email
column, you may pass a custom column name to the field’s make
method:
You may use the squared
method to display the image’s thumbnail with squared edges. Additionally, you may use the rounded
method to display the images with fully-rounded edges:
Heading Field
The Heading
field does not correspond to any column in your application’s database. It is used to display a banner across your forms and can function as a separator for long lists of fields:
If you need to render HTML content within the Heading
field, you may invoke the asHtml
method when defining the field:
Heading
fields are automatically hidden from the resource index page.
Hidden Field
The Hidden
field may be used to pass any value that doesn’t need to be changed by the user but is required for saving the resource:
Combined with default values, Hidden
fields are useful for passing things like related IDs to your forms:
ID Field
The ID
field represents the primary key of your resource’s database table. Typically, each Nova resource you define should contain an ID
field. By default, the ID
field assumes the underlying database column is named id
; however, you may pass the column name as the second argument to the make
method if necessary:
If your application contains very large integer IDs, you may need to use the asBigInt
method in order for the Nova client to correctly render the integer:
There should only be one ID
field configured per resource.
Image Field
The Image
field extends the File field and accepts the same options and configurations. The Image
field, unlike the File
field, will display a thumbnail preview of the underlying image when viewing the resource:
By default, the Image
field allows the user to download the linked file. To disable downloads, you may use the disableDownload
method on the field definition:
You may use the squared
method to display the image’s thumbnail with squared edges. Additionally, you may use the rounded
method to display its thumbnails with fully-rounded edges.
To learn more about defining file fields and handling uploads, check out the comprehensive file field documentation.
KeyValue Field
The KeyValue
field provides a convenient interface to edit flat, key-value data stored inside JSON
column types. For example, you might store profile information inside a JSON column type named meta
:
Given the field definition above, the following interface would be rendered by Nova:
Customizing KeyValue Labels
You can customize the text values used in the component by calling the keyLabel
, valueLabel
, and actionText
methods when defining the field. The actionText
method customizes the “add row” button text:
By default, Nova will never display a KeyValue
field on a resource index listing.
If you would like to disable the user’s ability to edit the keys of the field, you may use the disableEditingKeys
method to accomplish this. Disabling editing keys with the disableEditingKeys
method will automatically disable adding rows as well:
You may also remove the user’s ability to add new rows to the field by chaining the disableAddingRows
method onto the field’s definition:
In addition, you may also wish to remove the user’s ability to delete exisiting rows in the field. You may accomplish this by invoking the disableDeletingRows
method when defining the field:
Markdown Field
The Markdown
field provides a WYSIWYG Markdown editor for its underlying Eloquent attribute. Typically, this field will correspond to a TEXT
column in your database. The Markdown
field will store the raw Markdown text within the associated database column:
By default, Markdown fields will not display their content when viewing a resource’s detail page. Instead, the content will be hidden behind a “Show Content” link that will reveal the field’s content when clicked. You may specify that the Markdown field should always display its content by calling the alwaysShow
method on the field itself:
The Markdown field uses the league/commonmark
package to parse Markdown content. By default, it uses a parsing strategy similar to GitHub Flavoured Markdown, which does not allow certain HTML within the Markdown content. However, you can change the parsing strategy using the preset
method. Currently, the following built-in presets are default
, commonmark
, and zero
:
Using the preset
method, you may register and use custom preset implementations:
Markdown File Uploads
If you would like to allow users to drag-and-drop photos into the Markdown
field, you may chain the withFiles
method onto the field’s definition. When calling the withFiles
method, you should pass the name of the filesystem disk that photos should be stored on:
Nova will define two database tables to store pending and persisted Field
uploads. These two tables will be created automatically when you run Nova’s migrations during installation: nova_pending_field_attachments
and nova_field_attachments
.
Finally, in your routes/console.php
file, you should register a daily scheduled task to prune any stale attachments from the pending attachments table and storage. For convenience, Laravel Nova provides the job implementation needed to accomplish this:
MultiSelect Field
The MultiSelect
field provides a Select
field that allows multiple selection options. This field pairs nicely with model attributes that are cast to array
or equivalent:
On the resource index and detail pages, the MultiSelect
field’s “key” value will be displayed. If you would like to display the label values instead, you may invoke the displayUsingLabels
method when defining the field:
You may also display multi-select options in groups by providing an array structure that contains keys and label
/ group
pairs:
Number Field
The Number
field provides an input
control with a type
attribute of number
:
You may use the min
, max
, and step
methods to set the corresponding HTML attributes on the generated input
control:
You may also allow arbitrary-precision decimal values:
Password Field
The Password
field provides an input
control with a type
attribute of password
:
The Password
field will automatically preserve the password that is currently stored in the database if the incoming password field is empty. Therefore, a typical password field definition might look like the following:
Password Confirmation Field
The PasswordConfirmation
field provides an input that can be used for confirming another Password
field. This field will only be shown on forms and will not attempt to hydrate an underlying attribute on the Eloquent model:
When using this field, you should define the appropriate validation rules on the corresponding Password
field:
Select Field
The Select
field may be used to generate a drop-down select menu. The Select
menu’s options may be defined using the options
method:
On the resource index and detail pages, the Select
field’s “key” value will be displayed. If you would like to display the labels instead, you may use the displayUsingLabels
method:
You may also display Select
options in groups by providing an array structure that contains keys and label
/ group
pairs:
If you need more control over the generation of the Select
field’s options, you may provide a closure to the options
method:
Searchable Select Fields
At times it’s convenient to be able to search or filter the list of options available in a Select
field. You can enable this by invoking the searchable
method on the field:
After marking a select field as searchable
, Nova will display an input
field which allows you to filter the list of options based on its label:
Slug Field
Sometimes you may need to generate a unique, human-readable identifier based on the contents of another field, such as when generating a “slug” for a blog post title. You can automatically generate these “slugs” using the Slug
field:
By default, the field will convert a string like ‘My Blog Post’ to a slug like ‘my-blog-post’. If you would like the field to use underscores instead of dashes, you may use the separator
method to define your own custom “separator”:
Sparkline Field
The Sparkline
field may be used to display a small line chart on a resource’s index or detail page. The data provided to a Sparkline
may be provided via an array
, a callable
(which returns an array), or an instance of a Trend
metric class:
Using Trend Metrics
If the data needed by your Sparkline
field requires complicated database queries to compute, you may wish to encapsulate the data retrieval within a trend metric which can then be provided to the Sparkline
field:
In the example above, we’re providing the post’s id
to the metric’s constructor. This value will become the resourceId
property of the request that is available within the trend metric. For example, within the metric, we could access this post ID via $request->resourceId
:
When providing data to a Sparkline
field via a trend metric, the Sparkline
field will always use the first range defined in the ranges
method of the metric.
Customizing the Chart
If a bar chart better suits your data, you may invoke the asBarChart
method when defining the field:
By default, a Sparkline
will appear on a resource’s detail page. You can customize the dimensions of the chart using the height
and width
methods:
Status Field
The Status
field may be used to display a “progress state” column. Internally, Nova uses the Status
field to indicate the current state (waiting, running, or finished) of queued actions. However, you are free to use this field for your own purposes as needed:
The loadingWhen
and failedWhen
methods may be used to instruct the field which words indicate a “loading” state and which words indicate a “failed” state. In this example, we will indicate that database column values of waiting
or running
should display a “loading” indicator:
Stack Field
As your resource classes grow, you may find it useful to be able to group fields together to simplify your index and detail views. A Stack
field allows you to display fields like BelongsTo
, Text
, and others in a vertical orientation:
Stack
fields are not shown on forms, and are only intended for stacking lines of text on the index and detail resource views.
Line Fields
To gain more control over how the individual fields in a Stack
are displayed, you may use the Line
field, which provides methods for controlling the display of the line’s text. Line
fields offer the following presentational methods:
asHeading
asSubTitle
asSmall
asBase
In addition to the Line
field’s presentational methods, you may also pass any additional Tailwind classes to the field to customize the appearance of the Line
:
Passing Closures to Line Fields
In addition to passing BelongsTo
, Text
, and Line
fields to the Stack
field, you may also pass a closure. The result of the closure will automatically be converted to a Line
instance:
Tag Field
The Tag
field allows you to search and attach BelongsToMany
relationships using a tag selection interface. This field is useful for adding roles to users, tagging articles, assigning authors to books, and other similar scenarios:
Tag
fields will be displayed in a dropdown on the index view:
Previewing Tags
You may instruct the Tag
field to allow previewing the tag’s relation by invoking the withPreview
method on the field. This will display the related resource’s preview details in a modal:
Displaying Tags as Lists
Instead of displaying your tags as an inline group, you may instead display your tags as a list:
This allows tags to be displayed with their title, subtitle, and a configured image field:
Creating New Tags Inline
For convenience, when Tag
fields are shown on a resource create or update page, you may create the related resource inline via a modal window without leaving the creation / update page:
To enable this functionality, invoke the showCreateRelationButton
method when defining the field:
Adjusting the Inline Creation Modal’s Size
You may adjust the size of the modal using the modalSize
method:
Preloading Available Tags
To make existing tags more discoverable, you may show the user all available tags during resource creation or update by invoking the preload
method when defining the field:
Text Field
The Text
field provides an input
control with a type
attribute of text
:
Text fields may be further customized by setting any attribute on the field. This can be done by calling the withMeta
method and providing an extraAttributes
array containing key / value pairs of HTML attributes:
Text Field Suggestions
To offer auto-complete suggestions when typing into the Text
field, you may invoke the suggestions
method when defining the field. The suggestions
method should return an array
of suggestions:
Formatting Text as Links
To format a Text
field as a link, you may invoke the asHtml
method when defining the field:
Copying Text Field Values to the Clipboard
Sometimes you may wish to copy the value of a field into the system clipboard for pasting elsewhere. You can enable this on the detail view for a resource by calling the copyable
method on the Text
field:
Setting maxlength
on Text Fields
You may wish to indicate to the user that the content of a Text
field should be kept within a certain length. You can do this by using the maxlength
method on the field:
Nova will display the maximum length for the field along with a character counter. However, Nova will not enforce the maximum length. To instruct Nova to enforce the limit, you may call the enforceMaxlength
method on the field:
Textarea Field
The Textarea
field provides a textarea
control:
By default, Textarea fields will not display their content when viewing a resource’s detail page. Instead, the contents of the field will be hidden behind a “Show Content” link, which will reveal the content when clicked. However, if you would like, you may specify that the Textarea
field should always display its content by invoking the alwaysShow
method on the field:
You may specify the Textarea
height by invoking the rows
method on the field:
Textarea
fields may be further customized by setting any attribute on the field. This can be done by calling the withMeta
method and providing an extraAttributes
array containing key / value pairs of HTML attributes:
Setting maxlength
on Textarea Fields
You may wish to indicate to the user that the content of a Textarea
field should be kept within a certain length. You can do this by using the maxlength
method on the field:
Nova will display the maximum length for the field along with a character counter. However, Nova will not enforce the maximum length. To instruct Nova to enforce the limit, you may call the enforceMaxlength
method on the field:
Timezone Field
The Timezone
field generates a Select
field containing a list of the world’s timezones:
Trix Field
The Trix
field provides a Trix editor for its associated field. Typically, this field will correspond to a TEXT
column in your database. The Trix
field will store its corresponding HTML within the associated database column:
By default, Trix fields will not display their content when viewing a resource on its detail page. Instead, the content will be hidden behind a “Show Content” link, which will reveal the field’s content when clicked. If you would like, you may specify that the Trix field should always display its content by invoking the alwaysShow
method when defining the field:
Trix File Uploads
If you would like to allow users to drag-and-drop photos into the Trix
field, you may chain the withFiles
method onto the field’s definition. When calling the withFiles
method, you should pass the name of the filesystem disk that photos should be stored on:
In addition, Nova will define two database tables to store pending and persisted Field
uploads. These two tables will be created automatically when you run Nova’s migrations during installation: nova_pending_field_attachments
and nova_field_attachments
.
Finally, in your routes/console.php
file, you should register a daily scheduled task to prune any stale attachments from the pending attachments table and storage. For convenience, Laravel Nova provides the job implementation needed to accomplish this:
UI-Avatar Field
The UiAvatar
field does not correspond to any column in your application’s database. Instead, this field will generate a simple avatar containing the user’s initials. This field is powered by ui-avatars.com.
By default, the UiAvatar
image will be generated based on the value of the model’s name
column. However, if your user’s names are not stored in the name
column, you may pass a custom column name to the field’s make
method:
If necessary, you may invoke the resolveUsing
method to specify a closure that should be invoked to determine the name that should be used to generate the avatar:
You may use the squared
method to display the image’s thumbnail with squared edges. Additionally, you may use the rounded
method to display the images with fully-rounded edges:
Additional options available when defining UiAvatar
fields include:
Option | Method | Description |
---|---|---|
Font Size | fontSize(0.4) | Set a font size between 0.1 to 1 . |
Bold | bold() | Set font weight to bold. |
Background Color | backgroundColor('1D4ED7') | Set the hex color for the image background. |
Text Color | color('FFFFFF') | Set the hex color for the image text. |
URL Field
The URL
field renders URLs as clickable links instead of plain text:
The URL
field also supports customizing the generated link’s text by invoking the displayUsing
method when defining the field. The displayUsing
method accepts a closure that should return the link’s text:
By providing a closure as the second argument to the URL
field, you may use the field to render a link for a computed value that does not necessarily correspond to a column within the associated model’s database table:
Vapor File Field
The Vapor file field provides convenience and compatibility for uploading files when deploying applications to a serverless environment using Laravel Vapor:
When uploading a file using a VaporFile
field, Nova will first generate a signed storage URL on Amazon S3. Next, Nova will upload the file directly to temporary storage in the Amazon S3 bucket. When the resource is saved, Nova will move the file to permanent storage.
For more information on how file storage is handled for Vapor applications, please refer to the Laravel Vapor storage documentation.
Vapor Image Field
Vapor file fields provide convenience and compatibility for uploading image files when deploying applications in a serverless environment using Laravel Vapor:
Vapor image files support many of the same methods available to Image
fields.
To learn more about defining file fields and handling uploads, check out the additional file field documentation.
Validating Vapor Image / File Fields
In order to validate the size or other attributes of a Vapor file, you will need to inspect the file directly via the Storage
facade:
Computed Fields
In addition to displaying fields that are directly associated with columns in your database, Nova allows you to create “computed fields”. Computed fields may be used to display computed values that are not associated with a database column. Since they are not associated with a database column, computed fields may not be sortable
. These fields may be created by passing a callable (instead of a column name) as the second argument to the field’s make
method:
The model instance will be passed to the computed field callable, allowing you to access the model’s properties while computing the field’s value:
As you may have noticed in the example above, you may also use $this
to access the resource’s underlying model attributes and relationships.
By default, Vue will escape the content of a computed field. If you need to render HTML content within the field, invoke the asHtml
method when defining your field:
Customization
Readonly Fields
There are times where you may want to allow the user to only create and update certain fields on a resource. You can mark fields as “read only” by invoking the readonly
method on the field, which will disable the field’s corresponding input. You may pass a boolean argument to the readonly
method to dynamically control whether a field should be “read only”:
You may also pass a closure to the readonly
method, and the result of the closure will be used to determine if the field should be “read only”. The closure will receive the current NovaRequest
as its first argument:
If you only want to mark a field as “read only” when creating or attaching resources, you may use the isCreateOrAttachRequest
and isUpdateOrUpdateAttachedRequest
methods available via the NovaRequest
instance, respectively:
Required Fields
By default, Nova will use a red asterisk to indicate a field is required:
Nova does this by looking for the required
rule inside the field’s validation rules to determine if it should show the required state. For example, a field with the following definition would receive a “required” indicator:
When you have complex required
validation requirements, you can manually mark the field as required by passing a boolean to the required
method when defining the field. This will inform Nova that a “required” indicator should be shown in the UI:
In addition, you may also pass a closure to the required
method to determine if the field should be marked as required. The closure will receive an instance of NovaRequest
. The value returned by the closure will be used to determine if field is required:
The required()
method will only add a “required” indicator to the Nova UI. You must still define the related requirement rules()
that should apply during validation.
Nullable Fields
By default, Nova attempts to store all fields with a value, however, there are times where you may prefer that Nova store a null
value in the corresponding database column when the field is empty. To accomplish this, you may invoke the nullable
method on your field definition:
You may also set which values should be interpreted as a null
value using the nullValues
method, which accepts an array or a closure as its only argument:
Field Help Text
If you would like to place “help” text beneath a field, you may invoke the help
method when defining your field:
If necessary, you may include HTML within your field’s help text to further customize the help text:
Field Stacking
By default, Nova displays fields next to their labels on the create / update forms, however some fields like “Code”, “Markdown”, and “Trix” may benefit from the extra width that can be gained by placing the field under their corresponding labels. Fields can be stacked underneath their label using the stacked
method:
Full Width Fields
You may indicate that the field should be “full width” using the fullWidth
method:
Field Text Alignment
You may change the text alignment of fields using the textAlign
method:
The following alignments are valid:
left
center
right
Field Resolution / Formatting
The resolveUsing
method allows you to customize how a field is formatted after it is retrieved from your database but before it is sent to the Nova front-end. This method accepts a callback which receives the raw value of the underlying database column:
If you would like to customize how a field is formatted only when it is displayed on a resource’s “index” or “detail” pages, you may use the displayUsing
method. Like the resolveUsing
method, this method accepts a single callback:
Filterable Fields
The filterable
method allows you to enable convenient, automatic filtering functionality for a given field on resources, relationships, and lenses. The Nova generated filter will automatically be made available via the resource filter menu on the resource’s index:
The filterable
method also accepts a closure as an argument. This closure will receive the filter query, which you may then customize in order to filter the resource results to your liking:
The generated filter will be a text filter, select filter, number range filter, or date range filter depending on the underlying field type that was marked as filterable.
Dependent Fields
The dependsOn
method allows you to specify that a field’s configuration depends on one or more other field’s values. The dependsOn
method accepts an array
of dependent field attributes and a closure that modifies the configuration of the current field instance.
Dependent fields allow advanced customization, such as toggling read-only mode, validation rules, and more based on the state of another field:
To define dependent fields separately for creating and updating resources, you may use the dependsOnCreating
and dependsOnUpdating
methods.
Supported Dependent Fields
The following field types may depend on other fields:
- Audio
- BelongsTo
- Boolean
- BooleanGroup
- Color
- Code
- Country
- Currency
- Date
- DateTime
- File
- Heading
- Hidden
- Image
- KeyValue
- Markdown
- MorphTo
- Number
- Password
- PasswordConfirmation
- Select
- Status
- Textarea
- Text
- Timezone
- Trix
- URL
- VaporAudio
- VaporFile
- VaporImage
The following field types may not be depended upon by other fields since they do not live-report their changes to Nova:
- Audio
- Code
- File
- Image
- KeyValue
- Status
- Tag
- Trix
- VaporAudio
- VaporFile
- VaporImage
Toggling Field Visibility using dependsOn
One common use-case for dependent fields is toggling field visibility based on the value of another field. You can accomplish this using the hide
and show
methods:
Setting a Field’s Value Using dependsOn
Another common use-case for dependent fields is to set the value of a field based on the value of another field. You can accomplish this using the setValue
method:
Accessing Request Resource IDs
When interacting with dependent fields, you may retrieve the current resource and related resource IDs via the resource
method:
Extending Fields
Fields are “macroable”, which allows you to add additional methods to the Field
class at run time. The Field
class’ macro
method accepts a closure that will be executed when your macro is called. The macro closure may access the field’s other methods via $this
, just as if it were a real method of the field class. For example, the following code adds a toUpper
method to the Field
class:
Once the macro has been defined, it may be used when defining any field:
Macro Arguments
If necessary, you may define macros that accept additional arguments:
Macro on Specific Fields
You can also add a macro only to a specific type of Field
. For example, you might add a withFriendlyDate
macro to the DateTime
field class: