Reputation: 3692
I have a piece of code that I think is quite improvable.
In a DomainResource in the form() method, I have a circular relationship. (the only way I saw viable since I don't like the current ideas about having two guards in Filament)
The model has a relationship created with the User, but there are users that are not eligible.
So remove the //->relationship('user','name')
option
The code works for me but the logged in user with the ability to create more models can write (even if it doesn't work) in the field
$user = auth()->user();
return $form
->Select::make('user_id')
//->relationship('user','name')
->label('Administrador')
->options(function () use ($user){
if ($user->getRoleNames()->first() === 'super-admin') {
return User::role('owner')->pluck('name', 'id');
}
return User::where('id', $user->id)->pluck('name', 'id');
})
->searchable()
Any ideas?
After some time, I rewrote it a little better.
Select::make('user_id')
//->relationship('user','name')
->label('Administrador')
->options(function () {
if (auth()->user()->getRoleNames()->first() === 'super-admin')
{
return User::role('owner')->pluck('name', 'id');
}
return collect([
['name' => auth()->user()->name, 'id' => auth()->user()->id]
])->pluck('name', 'id');
})
->required()
->searchable()
Also, on resource class
public static function getEloquentQuery(): Builder
{
if (auth()->user()->hasAnyRole(['super-admin'])) {
return parent::getEloquentQuery()
->withoutGlobalScopes([
SoftDeletingScope::class,
]);
} else {
return parent::getEloquentQuery()
->withoutGlobalScopes([
SoftDeletingScope::class,
])
->whereBelongsTo(auth()->user());
}
}
It works, but of course, the combo list of the relationship comes out empty instead of filled with the value of the logged in user, and active. Come on, it's not very appropriate.
Upvotes: 0
Views: 12455
Reputation: 21
try adding default this way.
->default(auth()->user()->hasRole('super-admin')?null:auth()->user()->id)
Upvotes: 1