如何限制Filament选择字段仅显示登录用户关联的房产选项?
限制房源选择的房产为当前用户所有
问题背景
我的应用中,用户可添加住宅房产并基于该房产创建房源(Listing),一个用户可拥有多套房产。但当前房源关联房产的选择字段允许用户选择不属于自己的房产,需要将选项限制为仅当前用户添加的房产。
现有模型关联代码
Listing 模型关联
public function property(): BelongsTo { return $this->belongsTo(Property::class); }
Property 模型关联
public function user(): BelongsTo { return $this->belongsTo(User::class); } public function listing(): HasMany { return $this->hasMany(Listing::class); }
现有房源关联房产的选择字段代码
Select::make('property_id') ->relationship('property', 'house_no') ->label('Stand Number') ->createOptionForm([ Section::make('Details')->schema([ Select::make('area') ->options([ "Bloomingdale" => "Bloomingdale", 'Ashdown Park' => "Ashdown Park" ]), TextInput::make('house_no') ->required() ->label('House Number') ->numeric(), TextInput::make('street') ->nullable(), TextInput::make('families') ->label('Families On The Property') ->required() ->numeric(), ]),
解决方案
1. 限制选择框的房产选项为当前用户所有
在 relationship 方法中添加查询约束,过滤出当前用户的房产:
Select::make('property_id') ->relationship( name: 'property', titleAttribute: 'house_no', // 添加查询过滤,只显示当前用户的房产 modifyQueryUsing: fn (\Illuminate\Database\Eloquent\Builder $query) => $query->where('user_id', auth()->id()) ) ->label('Stand Number') ->createOptionForm([ // 原有表单字段... ])
2. 创建新房产时自动关联当前用户
如果允许用户在选择框中直接创建新房产,需要确保新创建的房产自动归属当前用户,否则新创建的房产不会出现在后续的选项中。有两种实现方式:
方式一:在创建表单中添加隐藏字段自动填充用户ID
在 createOptionForm 的schema中添加隐藏字段:
Section::make('Details')->schema([ // 原有字段... // 添加隐藏字段,自动填充当前用户ID \Filament\Forms\Components\Hidden::make('user_id') ->default(fn () => auth()->id()), ])
方式二:使用 createOptionUsing 手动处理创建逻辑
Select::make('property_id') ->relationship(/* ... */) ->label('Stand Number') ->createOptionForm([/* ... */]) ->createOptionUsing(function (array $data) { // 手动添加当前用户ID到创建数据中 $data['user_id'] = auth()->id(); return \App\Models\Property::create($data); })
注意事项
确保 Property 模型的 $fillable 属性包含 user_id,否则无法批量赋值:
class Property extends Model { protected $fillable = ['user_id', 'area', 'house_no', 'street', 'families']; // 其他模型代码... }
内容的提问来源于stack exchange,提问作者blackbeaches
相关产品推荐
相关产品推荐

