DEV Community

anditsung
anditsung

Posted on

3 2

remove already attach item on laravel nova

on nova resource class check the relatableQuery function

add this

 /**
     * Build a "relatable" query for the given resource.
     *
     * This query determines which instances of the model may be attached to other resources.
     *
     * @param  \Laravel\Nova\Http\Requests\NovaRequest  $request
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public static function relatableQuery(NovaRequest $request, $query)
    {
        if ($request->is('nova-api/*/*/attach*/*')) {
            if (! $request->current) {
                $query = self::removeAlreadyAttachItem($query, $request);
            }
            else if ($request->current && ! $request->first) {
                $query = self::removeAlreadyAttachItem($query, $request);
            }
        }

        return parent::relatableQuery($request, $query);
    }
Enter fullscreen mode Exit fullscreen mode

remove already attach item function

private static function removeAlreadyAttachItem($query, $request)
    {
        $relationName = Str::plural(Str::snake(class_basename($query->getModel())));

        $model = $request->findResourceOrFail()->model();

        $model->load($relationName);

        $items = $model->getRelation($relationName)->map(function ($model) {
            return collect($model->toArray())->only('id')->all();
        });

        return $query->whereNotIn('id', $items);
    }
Enter fullscreen mode Exit fullscreen mode

Image of Docusign

Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay