简体   繁体   中英

Laravel Nova extra 'images' field on forms without actual database column

Creating extra field 'images' resource forms usually throws ' column not found ' type database level error. But I need that type of extra field on the resource forms for some business logic under the hood when the create/update form is submitted.

I tried using removeNonCreationFields method on resource to remove that field column from saving to database but does not work and still throws error.

Please note that ->hideWhenCreating() or ->readonly() is not relevant as I need to interact on that field on create/delete forms.

Is there any other way to make such situation success with extra fields? Please help. Thanks.

My solution was:

app/Nova/Post.php

/**
 * @param  NovaRequest  $request
 * @param  \Illuminate\Database\Eloquent\Model  $model
 * @param  \Illuminate\Support\Collection  $fields
 * @return array|void
 */
protected static function fillFields(NovaRequest $request, $model, $fields)
{
    $fillFields = parent::fillFields($request, $model, $fields);

    // first element should be model object
    $modelObject = $fillFields[0];

    // remove all extra non-database attributes from the model
    unset($modelObject->to_profile_gallery);

    // I am not sure it will work if we unset on $model parameter and return it
    // But you should try first doing so on $model parameter and return $model

    return $fillFields;
}

Then you should use two functions, one for how to save in database and another for how to retrieve that specific data from database. Use these on the extra Field.

->fillUsing(function($request, $model, $attribute, $requestAttribute){
   // during creation photos are handled by Nova Resource Observer
   if($model->type !== post_type_photo()) return;
   // run only for update request
   FilepondHelper::handleMediaFillUsingCallback(PostMediaTag::photos, true, $request, $model, $attribute, $requestAttribute); // only update
})
->resolveUsing(function($value, $resource, $attribute) use($request){
   return FilepondHelper::handleMediaResolveUsingCallback(PostMediaTag::photos, $value, $resource, $attribute, $request);
}),

Hoping this will solve your issue. Thanks

Hasnat approach worked perfectly for my case. I wanted to have one special field when creating a resource only for internal logic, which should be ignored/discarded and not related in any way to a database field. Thanks!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM