Benjacho / belongs-to-many-field-nova

Belongs To Many field Laravel nova to represent many to many relationship in field.
MIT License
157 stars 81 forks source link

Replication support #126

Open nubian-sk opened 1 year ago

nubian-sk commented 1 year ago

To be able to pre-fill options during resource replication, I use this code in my App\Nova\ProductHelp.class. Anyone can provide a better (less dirty) alternative. My BelongsToMany relation is "Language".

    public function replicate()
    {
        return tap(parent::replicate(), function ($resource) {
            $model = $resource->model();
            /*
                URL replication example:
                /nova-api/product-helps/creation-fields?editing=true&editMode=create&inline=false&fromResourceId=120&viaResource=&viaResourceId=&viaRelationship=
            */
            $currentReplicatedID = request("fromResourceId");
            if (is_numeric($currentReplicatedID) && $currentReplicatedID > 0) {
                $languages = DB::select("SELECT * FROM `language_product_help` LEFT JOIN languages ON language_product_help.language_id = languages.id WHERE product_help_id = {$currentReplicatedID}");
                $languages = json_encode($languages);
                $model->languages = (string) $languages;
            }
        });
    }