resolveModel($type, $id); if (! $model || $model->organization_id !== $this->organization->id) { return; } $alreadyLinked = RelatedItem::forItem($this->item)->get()->contains( fn (RelatedItem $edge) => $this->sameModel($edge->otherItem($this->item), $model) ); if ($alreadyLinked || $this->sameModel($model, $this->item)) { return; } RelatedItem::create([ 'item_type' => $this->item->getMorphClass(), 'item_id' => $this->item->getKey(), 'related_item_type' => $model->getMorphClass(), 'related_item_id' => $model->getKey(), 'created_by' => auth()->id(), ]); $this->search = ''; } public function unlink(int $edgeId): void { RelatedItem::forItem($this->item)->whereKey($edgeId)->delete(); } public function with(): array { $linkedEdges = RelatedItem::forItem($this->item)->with(['item', 'relatedItem'])->latest()->get(); return [ 'linked' => $linkedEdges->map(fn (RelatedItem $edge) => [ 'edge_id' => $edge->id, 'model' => $edge->otherItem($this->item), ])->filter(fn ($row) => $row['model'] !== null), 'results' => $this->search !== '' ? $this->searchCandidates() : collect(), ]; } protected function searchCandidates() { $linkedKeys = RelatedItem::forItem($this->item)->get() ->map(fn (RelatedItem $edge) => $this->modelKey($edge->otherItem($this->item))) ->filter() ->all(); $selfKey = $this->modelKey($this->item); $results = collect(); $results = $results->merge( Password::where('organization_id', $this->organization->id) ->where('name', 'like', "%{$this->search}%") ->limit(5)->get() ); $results = $results->merge( FlexibleAsset::where('organization_id', $this->organization->id) ->where('name', 'like', "%{$this->search}%") ->limit(5)->get() ); $results = $results->merge( Document::where('organization_id', $this->organization->id) ->whereNotNull('content')->where('content', '!=', '') ->where('name', 'like', "%{$this->search}%") ->limit(5)->get() ); return $results->reject(fn ($model) => in_array($this->modelKey($model), $linkedKeys, true) || $this->modelKey($model) === $selfKey) ->values(); } protected function resolveModel(string $type, int $id): ?Model { return match ($type) { Password::class => Password::find($id), FlexibleAsset::class => FlexibleAsset::find($id), Document::class => Document::find($id), default => null, }; } protected function modelKey(?Model $model): ?string { return $model ? $model->getMorphClass().':'.$model->getKey() : null; } protected function sameModel(?Model $a, ?Model $b): bool { return $this->modelKey($a) !== null && $this->modelKey($a) === $this->modelKey($b); } }; ?>

Éléments liés

@if ($search !== '')
@forelse ($results as $result) @empty
Aucun résultat.
@endforelse
@endif