如何修改选择器仅显示未共享当前文档的用户(含pivot table document_user)
First, let’s confirm your model relationships are set up correctly (since you’re using a pivot table):
In your Document model:
public function users() { return $this->belongsToMany(User::class); // Add ->using(DocumentUser::class) if you have a custom pivot model }
In your User model:
public function documents() { return $this->belongsToMany(Document::class); }
Step 1: Eager Load Shared Users in Controller
To avoid performance issues (N+1 database queries), eager load the users already linked to the document when fetching it in your controller:
$document = Document::with('users')->findOrFail($documentId); $company = Company::findOrFail($companyId); // Assuming you already fetch this return view('your-view-path', compact('document', 'company'));
Step 2: Modify the Blade Template
Update your select dropdown to exclude users who already have access to the document:
<select type="text" name="user" class="uk-select"> <option disabled selected>Choose from contacts</option> @foreach($company->users as $contact) @if(!$document->users->contains($contact->id)) <option value="{{ $contact->id }}">{{ $contact->first_name }} {{ $contact->last_name }}</option> @endif @endforeach </select>
How This Works:
$document->users->contains($contact->id)checks if the current contact is already associated with the document via thedocument_userpivot table.- The
!negates that check, so we only render options for users who haven’t been granted access yet.
Optional Optimization
If you prefer cleaner template code, precompute the list of unshared users in your controller:
$sharedUserIds = $document->users->pluck('id')->toArray(); $unsharedUsers = $company->users->whereNotIn('id', $sharedUserIds); return view('your-view-path', compact('unsharedUsers'));
Then loop directly over the filtered list in your view:
<select type="text" name="user" class="uk-select"> <option disabled selected>Choose from contacts</option> @foreach($unsharedUsers as $contact) <option value="{{ $contact->id }}">{{ $contact->first_name }} {{ $contact->last_name }}</option> @endforeach </select>
内容的提问来源于stack exchange,提问作者Philipp Kishkovarov
相关产品推荐
相关产品推荐

