4

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?

Wai Yan Hein
  • 13,651
  • 35
  • 180
  • 372

3 Answers3

11

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.

Remko
  • 968
  • 6
  • 19
4

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;
            }),
    ];
}
Igor
  • 755
  • 1
  • 10
  • 22
2

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()
r00t
  • 468
  • 3
  • 10