[go: up one dir, main page]

DEV Community

anditsung
anditsung

Posted on

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

Top comments (0)