DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 963,864 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
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)

Update Your DEV Experience Level:

Settings

Go to your customization settings to nudge your home feed to show content more relevant to your developer experience level. πŸ›