Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a Laravel Nova field to display as readonly or protected?

Tags:

laravel-nova

Within Laravel Nova (v1.0.3), there are several methods that grant fine-grained control of the visibility of a resource field (canSee, showOnDetail, etc.). I can't find any methods that control if a field is editable. How can I display a field, but prevent the user from being able to edit it (make it readonly)?

For example, I'd like to display the "Created At" field, but I don't want the user to be able to change it.

like image 549
Matt Avatar asked Aug 22 '18 21:08

Matt


4 Answers

This capability was added in v1.1.4 (October 1, 2018).

  • Allow setting any attribute on text and textarea fields

Example usage:

Text:: make('SomethingImportant')
    ->withMeta(['extraAttributes' => [
          'readonly' => true
    ]]),
like image 161
Matt Avatar answered Nov 04 '22 00:11

Matt


July 2021, For Nova version 3.0, the readonly method can accept different types of arguments

Default:

Text::make('Email')->readonly()

Direct boolean:

Text::make('Email')->readonly(true/false)

Closure:

Text::make('Email')->readonly(function ($request) {
    return !$request->user()->isNiceDude();
}

Read more here https://nova.laravel.com/docs/3.0/resources/fields.html#readonly-fields

like image 20
MohKoma Avatar answered Sep 20 '22 14:09

MohKoma


As of Nova >2.0 you can use the readonly method with a callback and checking for the resource:

Text::make("Read Only on Update")
    ->readonly(function() {
        return $this->resource->id ? true : false;
    }),

or even better:

Text::make("Read Only on Update")
    ->readonly(function() {
        return $this->resource->exists;
    }),
like image 13
bernhardh Avatar answered Nov 04 '22 00:11

bernhardh


As of v2.0.1, readonly() is native and accepts a callback, closure or boolean and can simply be called as:

Text::make('Name')->readonly(true)

This may have been added prior to this version but the changelog does not specify if this is the case.

Nova v2.0 documentation

like image 12
neil Avatar answered Nov 04 '22 02:11

neil