{"id":44395140,"url":"https://github.com/inspheric/nova-defaultable-fields","last_synced_at":"2026-02-12T03:03:15.624Z","repository":{"id":56992067,"uuid":"184887216","full_name":"inspheric/nova-defaultable-fields","owner":"inspheric","description":"Laravel Nova Defaultable Fields","archived":false,"fork":false,"pushed_at":"2021-06-17T14:08:43.000Z","size":42,"stargazers_count":53,"open_issues_count":3,"forks_count":2,"subscribers_count":4,"default_branch":"master","last_synced_at":"2025-10-21T09:54:53.568Z","etag":null,"topics":["laravel","laravel-nova","laravel-nova-field","laravel-package","nova"],"latest_commit_sha":null,"homepage":"https://novapackages.com/packages/inspheric/nova-defaultable","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/inspheric.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2019-05-04T11:40:22.000Z","updated_at":"2024-06-06T11:07:50.000Z","dependencies_parsed_at":"2022-08-21T12:50:46.882Z","dependency_job_id":null,"html_url":"https://github.com/inspheric/nova-defaultable-fields","commit_stats":null,"previous_names":[],"tags_count":3,"template":false,"template_full_name":null,"purl":"pkg:github/inspheric/nova-defaultable-fields","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/inspheric%2Fnova-defaultable-fields","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/inspheric%2Fnova-defaultable-fields/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/inspheric%2Fnova-defaultable-fields/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/inspheric%2Fnova-defaultable-fields/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/inspheric","download_url":"https://codeload.github.com/inspheric/nova-defaultable-fields/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/inspheric%2Fnova-defaultable-fields/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":29355855,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-02-12T01:03:07.613Z","status":"online","status_checked_at":"2026-02-12T02:00:06.911Z","response_time":55,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["laravel","laravel-nova","laravel-nova-field","laravel-package","nova"],"created_at":"2026-02-12T03:03:11.657Z","updated_at":"2026-02-12T03:03:15.614Z","avatar_url":"https://github.com/inspheric.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Laravel Nova Defaultable Fields\nPopulate default values for Nova fields when creating resources and **now supports resource actions (since v1.2)!**\n\n[![Latest Version on Packagist](https://img.shields.io/packagist/v/inspheric/nova-defaultable.svg?style=flat-square)](https://packagist.org/packages/inspheric/nova-defaultable)\n[![Total Downloads](https://img.shields.io/packagist/dt/inspheric/nova-defaultable.svg?style=flat-square)](https://packagist.org/packages/inspheric/nova-defaultable)\n\n## Installation\n\nInstall the package into a Laravel app that uses [Nova](https://nova.laravel.com) with Composer:\n\n**Note: This package is currently incompatible with Nova version 3.4.0 and above.**\n\n```bash\ncomposer require inspheric/nova-defaultable\n```\n\n(Optional) If you want to use the `defaultLast()` method when creating resources ([see below](#default-the-last-saved-value)), you need to add the trait `Inspheric\\NovaDefaultable\\HasDefaultableFields` to your base Resource class (located at `app\\Nova\\Resource.php`):\n\n```php\nuse Inspheric\\NovaDefaultable\\HasDefaultableFields;\n\nabstract class Resource extends NovaResource\n{\n    use HasDefaultableFields;\n\n    // ...\n}\n```\n\n(Optional) If you want to use the `defaultLast()` method on resource actions, you need to add the trait `Inspheric\\NovaDefaultable\\HasDefaultableActionFields` to **every** Action class (located at `app\\Nova\\Actions\\`, one by one) that you wish to use defaultable fields on:\n\n```php\nuse Inspheric\\NovaDefaultable\\HasDefaultableActionFields;\n\nclass YourAction extends Action\n{\n    use HasDefaultableActionFields;\n\n    // ...\n}\n```\n\n## Basic Usage\n\nWhen creating resources or running resource actions, there may be values which can be defaulted to save the user time, rather than needing to be entered into a blank form every time. This could include populating the `user_id` on a resource that the current user owns, repeating the same 'parent' record for several new records in a row, starting with a checkbox in a checked state, or populating an incrementing value, e.g. an invoice number.\n\nThis package plugs into existing fields and provides two simple methods to supply a default value.\n\n*Note:* The defaultable behaviour below is only applicable on the resource's 'create' or 'attach' form, or on action requests. Fields will not be defaulted on 'update' or 'update-attached' requests; however, the last used value will be stored on any successful save request, and will be defaulted on a later 'create'/'attach' request.\n\n### Default any value\n\nUse the `default($value)` method on any standard Nova field to populate a simple value, e.g.\n\n```php\nText::make('Name')\n    -\u003edefault('Default Name'),\n```\n\nor:\n```php\nBoolean::make('Active')\n    -\u003edefault(true),\n```\nThe `default()` method can also take a callback as the first parameter, which will return the value to be populated:\n\n```php\nText::make('Name')\n    -\u003edefault(function(NovaRequest $request) {\n        return $request-\u003euser()-\u003ename.'\\'s New Resource';\n    }),\n```\n\n### Special cases\n#### Default a BelongsTo field\n\nTo use the `default()` method on a Nova `BelongsTo` field, you can supply either:\n\n* An instance of an Eloquent model, e.g.\n\n    ```php\n    // $author = $request-\u003euser();\n\n    BelongsTo::make('Author')\n        -\u003edefault($author),\n    ```\n\n* The primary key of the related record, e.g.\n\n    ```php\n    // $id = 1;\n\n    BelongsTo::make('Author')\n        -\u003edefault($id),\n    ```\n    \n    *Note:* This is a convenience only and should not be relied upon for enforcing that an author can only edit their own posts, etc.\n\n#### Default a MorphTo field\n\nTo use the `default()` method on a Nova `MorphTo` field, you can supply either:\n\n* An instance of an Eloquent model (the simplest option), e.g.\n\n    ```php\n    // $post = App\\Post::find(1);\n\n    MorphTo::make('Commentable')\n        -\u003etypes([\n            Post::class,\n            Video::class,\n        ])\n        -\u003edefault($post),\n    ```\n\n* An array containing the primary key and the morph type, e.g.\n\n    ```php\n    // $postId = 1;\n\n    MorphTo::make('Commentable')\n        -\u003etypes(...)\n        -\u003edefault([$postId, App\\Nova\\Post::class]), // The Resource class or class name\n    ```\n    or:\n    ```php\n    MorphTo::make('Commentable')\n        -\u003etypes(...)\n        -\u003edefault([$postId, App\\Post::class]), // The Eloquent model class or class name\n    ```\n    or:\n    ```php\n    MorphTo::make('Commentable')\n        -\u003etypes(...)\n        -\u003edefault([$postId, 'posts']), // The uriKey string\n    ```\n\n* An instance of a Nova Resource, e.g.\n\n    ```php\n    // $postResource = Nova::newResourceFromModel(App\\Post::find(1));\n\n    MorphTo::make('Commentable')\n        -\u003etypes(...)\n        -\u003edefault($postResource),\n    ```\n\n### Default the last saved value\n\nUse the `defaultLast()` method to cache the last value that was saved for this field and repopulate it the next time this field is resolved:\n\n```php\nText::make('Name')\n    -\u003edefaultLast(),\n```\n\nThis will be useful in the following scenarios:\n* After saving (create or update) one resource, the last value will be repopulated when creating the next new resource.\n* After running an action on one resource, the last value will be repopulated when running the same action on another resource.\n\nThe value is cached uniquely to the user, resource class, action name (if applicable), field, and attribute. The default cache duration is an hour, but this is customisable (see [Configuration](#configuration)).\n\nThis can be used, for example, to speed up creating multiple resources one after another with the same parent resource, e.g.\n\n```php\nBelongsTo::make('Author')\n    -\u003edefaultLast(),\n```\n\n*Note:* The `defaultLast()` method handles the morph type for `MorphTo` fields automatically.\n\n*Note:* Because the \"Select Action\" dropdown is not refreshed after an action is run on the index view, `defaultLast()` cannot repopulate each last value if you run the action several times while on the same index view. If you need the value to be repopulated every time on the index view, you can set the property `$refreshIndex = true` on the action class, e.g.\n\n```php\nclass YourAction extends Action\n{\n    protected $refreshIndex = true;\n    \n    public function handle(ActionFields $fields, Collection $models)\n    {\n        // ...\n    }\n}\n```\n\nWhen the action is run from the index view, it will return a redirect response to refresh the whole page. It has no effect if the action is run from the detail view, because Nova already refreshes the page after each action automatically.\n\n\u003e :confounded: I don't really like this workaround but can't think of an alternative. I would be happy to hear other ideas.\n\n*Note:* If you set `$refreshIndex = true`, and you return your own [action response](https://nova.laravel.com/docs/2.0/actions/defining-actions.html#action-responses) from the action's `handle()` method, it will be ignored on the index view because it is overridden by the redirect response. It will behave as normal on the detail view.\n\n### Display using a callback\n\nBoth the `default($value, callable $callback = null)` and `defaultLast(callable $callback = null)` methods can take a callback as the final parameter which will transform the defaulted value (whether retrieved from cache or passed to the `default()` method) before it is populated, e.g.\n\n```php\n$lastInvoiceNumber = auth()-\u003euser()-\u003elast_invoice_number;\n\nNumber::make('Invoice Number')\n    -\u003edefault($lastInvoiceNumber, function($value, NovaRequest $request) {\n        return $value + 1; // Note: Here the $value came from $lastInvoiceNumber\n    }),\n```\n\n```php\nNumber::make('Invoice Number')\n    -\u003edefaultLast(function($value, NovaRequest $request) {\n        return $value + 1; // Note: Here the $value came from the cache\n    }),\n```\n\nThis can be used, for example, to increment a value each time a new resource is created. *Note:* This is a convenience only and should not be relied upon for uniqueness or strictly sequential incrementing.\n\n### Default last value _or_ static value\n\nIf the user does not yet have a 'last' value stored, or the cache has expired, the value for `defaultLast()` will be blank. If you want to fall back to another value if nothing is found in the cache, you can simply do this in the callback, e.g.\n\n```php\nBelongsTo::make('Author')\n    -\u003edefaultLast(function($value, NovaRequest $request) {\n        return $value ?: $request-\u003euser()-\u003eid;\n    }),\n```\n\nIn this example, the author of the first record created will default to the current user, but every subsequent record will default to the last value saved.\n\n## Advanced Usage\n### Extend\n\nOut of the box, the package supports all standard Nova fields which have a single value and can be edited on the 'create' form. There is specific behaviour for the `BelongsTo` and `MorphTo` fields, as described above.\n\nThis package does not support any of the fields that implement `Laravel\\Nova\\Contracts\\ListableField`, such as `HasMany`, `BelongsToMany` etc., or fields that extend `Laravel\\Nova\\Fields\\File`, such as `File`, `Image` or `Avatar`.\n\nAny custom field with a single value which extends `Laravel\\Nova\\Fields\\Field` *should* work without customisation. However, if required, you can extend the behaviour to support custom field types which need additional metadata to be populated.\n\nThe `DefaultableField::extend()` method takes the class name of your custom field and a callback which receives `$field` (the resolved `Field` instance) and `$value` (the value that was passed to `default()` or retrieved from cache by `defaultLast()`).\n\nYou **must** return the `$field` from your callback, and it is suggested that you use `$field-\u003ewithMeta()` to send the appropriate metadata that will cause the field to be prepopulated, e.g. in your `App\\Providers\\NovaServiceProvider`:\n\n```php\nuse Inspheric\\NovaDefault\\DefaultableField;\n\nDefaultableField::extend(YourField::class, function($field, $value) {\n    return $field-\u003ewithMeta([\n        'value' =\u003e $value, // This line is usually required to populate the value\n        'yourMeta' =\u003e 'yourValue', // Any additional meta depends on your custom field type\n    ]);\n});\n```\n\n*Note:* If you are using `extend()` as above, the basic defaulting functionality of this package is *completely* overridden, so you must ensure that your own callback sets the field's value correctly. This is usually done by setting the `'value'` meta key, but your field may differ, or may need additional meta keys to be set (such as `'belongsToId'` in the case of a `BelongsTo` field).\n\nYou can pass an array of field types as the first argument to use the same callback on all of them, i.e.\n\n```php\nDefaultableField::extend([YourField::class, YourOtherField::class], function($field, $value) {\n    // ...\n});\n```\n\nAlternatively, `Inspheric\\NovaDefault\\DefaultableField` is macroable, so you can add a macro and then use the macro's name as a string as the second argument for the `extend()` method, i.e.\n\n```php\nDefaultableField::macro('handleYourField', function($field, $value) {\n    // ...\n});\n\nDefaultableField::extend(YourField::class, 'handleYourField');\nDefaultableField::extend(YourOtherField::class, 'handleYourField');\n```\n\n## Configuration\n\nThe configuration can be published using:\n```bash\nphp artisan vendor:publish --provider=\"Inspheric\\NovaDefaultable\\DefaultableServiceProvider\" --tag=\"config\"\n```\n\nThe configuration file contains two keys:\n* `cache.key` - The key to use to store the \"last\" values in the cache. Defaults to 'default_last' and will be prepended to the authenticated user ID, resource class and field attribute for uniqueness.\n* `cache.ttl` - The time to store the last values in the cache, in seconds. Defaults to one hour (60 * 60).\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Finspheric%2Fnova-defaultable-fields","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Finspheric%2Fnova-defaultable-fields","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Finspheric%2Fnova-defaultable-fields/lists"}