You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改选择器仅显示未共享当前文档的用户(含pivot table document_user)

Solution to Filter Unshared Users in Select Dropdown

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 the document_user pivot 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 11:11:54