Reputation: 14801
I am developing a Web Application using Laravel Nova. Laravel Nova is quite new. I am now having problem with database relationship and Fields. I like to ignore a field from database operations. This is my scenario.
In the Job resource, I have this fields method
public function fields(Request $request)
{
return [
ID::make()->sortable(),
Text::make('Name', 'name'),
Text::make('Email', 'email'),
Select::make('Contract Types')->options($array_of_options)//I want to ignore this field
];
}
As you can see, the last field is Contract Types.
When I create a new job from Dashboard, it is throwing error because there is no contract_types column on the Job model. I like to ignore that field from database operation. How can I get it?
Upvotes: 4
Views: 5382
Reputation: 131
There is \Laravel\Nova\Fields\Unfillable
interface for that purpose.
It's possible to create a custom Field. It has to extend the needed native Nova field and implement an Unfillable
interface.
Then Nova will not save the field to an entity attribute
Upvotes: 1
Reputation: 1131
You can make an own custom handling of the Field data, just use fillUsing()
method of the Field class. An example
public function fields(Request $request)
{
return [
ID::make()->sortable(),
Text::make('Name', 'name'),
Text::make('Email', 'email'),
Select::make('Contract Types', 'unique_key_for_model')
->options($array_of_options)
->fillUsing(function(NovaRequest $request, $model, $attribute, $requestAttribute) {
/*
$request->input('unique_key_for_model') // Value of the field
$model->unique_key_for_model // DOES NOT exists, so no errors happens
*/
// or just return null;
return null;
}),
];
}
Upvotes: 5
Reputation: 958
The accepted answer is not completely correct. It prevents storing the value in the database but also completely hides the field in the form. In some weird cases you might want to show a field that is not stored.
My suggestion would be to add the following to the resource (or put in somewhere more re-usable if you want this in multiple resources):
public static function fill(NovaRequest $request, $model)
{
return static::fillFields(
$request, $model,
(new static($model))->creationFieldsWithoutReadonly($request)->reject(function ($field) use ($request) {
return in_array('ignoreOnSaving', $field->meta);
})
);
}
In the relevant field(s) you could than add:
->withMeta(['ignoreOnSaving'])
This will give you a field to fill without saving it in the model.
Upvotes: 11
Reputation: 466
According to the docs https://nova.laravel.com/docs/1.0/resources/fields.html#showing-hiding-fields
Select::make('Contract Types')
->options($array_of_options)
->hideWhenCreating()
Upvotes: 2